Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript split() method resulting in undefined

I'm working on a simple program that will select a random string from an array.

I started with a predefined array, but about halfway through wondered if it wouldn't be simpler (or more elegant) to use a text file (.txt), since I have a bit over 1000 items.

I found this solution here (for which I take no credit) and it is working for me...

function readTextFile(file) {
    var items = [];
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function() {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status === 0)
            {
                var items = rawFile.responseText.split('\n');
                alert(items[0]);
            }
        }
    };
    rawFile.send(null);
}

readTextFile('source.txt');

...to an extent.

I want the array items[] to contain one line per item. In other words I want to split per new line. However, all array items are undefiend after items[0] when I use split('\n').

items[0] in the example above becomes the first sentence, so that much is correct. If I want to alert items[1] I get undefined.

If I use some other split point, such as split(''), it works correctly, separating each character per item ONLY until the line breaks, after which point I get undefined again.

Let's say the first line of the .txt is "asd": so 'asd' is defined in array as :

items[0] = 'a'
items[1] = 's'
items[2] = 'd'
items[3] = undefined

This is what I would get. Where am I wrong?

Contents of text file:

asfe
asdasdasd
asdasd

fgfg
like image 239
Tiago Avatar asked Jan 12 '14 14:01

Tiago


1 Answers

Try adding a String cast:

var items = String(rawFile.responseText).split('\n');

like image 180
Leonardo Moreno Avatar answered Oct 06 '22 01:10

Leonardo Moreno