JavaScript split() 方法导致未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21075692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:59:22  来源:igfitidea点击:

JavaScript split() method resulting in undefined

javascriptjqueryarrayssplittext-files

提问by Tiago

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.

我从一个预定义的数组开始,但在大约一半的时候想知道使用 a 是否更简单(或更优雅)text file (.txt),因为我有 1000 多个项目。

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').

我希望array items[]每个项目包含一行。换句话说,我想按新行拆分。但是,items[0]当我使用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.

items[0]在上面的例子中变成了第一句话,所以说的很对。如果我想alert items[1]我得到未定义。

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.

如果我使用其他一些分割点,例如split(''),它可以正常工作,仅将每个项目的每个字符分开直到换行,然后我再次未定义。

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

假设 : 的第一行,.txt is "asd"因此 'asd' 在数组中定义为:

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

回答by Leonardo Moreno

Try adding a String cast:

尝试添加一个字符串转换:

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

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

回答by Shadow Wizard is Ear For You

After some messing around with this I believe the problem is with your text editor that save the file with line breaks consisting of \rinstead of \n, maybe Unix based server?

经过一番折腾之后,我相信问题出在您的文本编辑器上,该编辑器使用换行符组成的换行符保存文件,\r而不是\n基于 Unix 的服务器?

Anyway, you can replace those and it should work:

无论如何,您可以替换它们并且它应该可以工作:

var rawText = rawFile.responseText;
rawText = rawText.replace(/\r\n/g, "\n");
rawText = rawText.replace(/\n\r/g, "\n");
rawText = rawText.replace(/\r/g, "\n");
var items = rawText.split('\n');

回答by BenM

Probably because there's a blank row at the end of the responseText. Try using trim():

可能是因为responseText. 尝试使用trim()

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