Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/381.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript:加载.txt文件并拆分后,数组末尾的空元素_Javascript - Fatal编程技术网

JavaScript:加载.txt文件并拆分后,数组末尾的空元素

JavaScript:加载.txt文件并拆分后,数组末尾的空元素,javascript,Javascript,我有一个words.txt文件,看起来像这样: account arm cotton zoo ["a","c","c","o","u","n","t"] 我使用XMLHttpRequest加载该文件,使用以下代码分别创建包含每行的数组列表: var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status ==

我有一个words.txt文件,看起来像这样:

account
arm
cotton
zoo
["a","c","c","o","u","n","t"]
我使用XMLHttpRequest加载该文件,使用以下代码分别创建包含每行的数组列表:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    //this is where I split it
    wordlist = this.responseText.split('\n');
  }
};
xhttp.open('GET', 'words.txt', true);
xhttp.send();
然后我从列表中随机选择一个元素,比如说
account
,然后按
''
将其拆分,以获得所有单个字符:

word = wordlist[randomIndex].split('');
我预计结果如下:

account
arm
cotton
zoo
["a","c","c","o","u","n","t"]
但是,结果是这样的,在末尾有一个额外的空字符串:

["a","c","c","o","u","n","t",""]

如何正确处理此问题?

Windows样式的换行符不仅仅是\n,它们是\r\n。因此,如果文件是以Windows样式创建的,则在\n处拆分仍将保留尾随字符

您只需在按字符分割之前修剪字符串:

word = wordlist[randomIndex].trim().split('');

Windows样式的换行符不仅仅是\n,它们是\r\n。因此,如果文件是以Windows样式创建的,则在\n处拆分仍将保留尾随字符

您只需在按字符分割之前修剪字符串:

word = wordlist[randomIndex].trim().split('');

您还可以
word=newarray.from(wordlist[randomIndex].trim())@JDunken True。无论哪种情况,结果都是一样的;我只是坚持OP选择使用拆分。这不是批评,只是给路人一个选择。有理由选择这两种方法中的一种吗?@IceMetalPunk当然有。这并不是关于
数组的评论。从
拆分(“”)
。扩展语法
[…wordlist[randomIndex].trim()]
更好,但仍然不是防弹的。您也可以
word=new Array.from(wordlist[randomIndex].trim())@JDunken True。无论哪种情况,结果都是一样的;我只是坚持OP选择使用拆分。这不是批评,只是给路人一个选择。有理由选择这两种方法中的一种吗?@IceMetalPunk当然有。这并不是关于
数组的评论。从
拆分(“”)
。扩展语法
[…wordlist[randomIndex].trim()]
做得更好,但仍然不是防弹的。您可能想看看…您可能想看看。。。