简体   繁体   English

JavaScript split添加了一个额外的空数组项?

[英]JavaScript split add an extra empty array item?

The following code reads a file and turned each line into array items: 以下代码读取一个文件,并将每一行变成数组项:

fs.readFile('en.txt', 'utf8', function (err, data) {
  if (err) {
    return console.log(err)
  }

  enStrings = data.split(/[\r\n]+/g)
}

en.txt looks like this: en.txt看起来像这样:

Line 1
Line 2
Line 3

But I'm puzzled. 但是我很困惑。 console.log(enStrings) outputs this: console.log(enStrings)输出以下内容:

[ 'Line 1', 'Line 2', 'Line 3', '' ]

Why is that last empty item being added? 为什么要添加最后一个空项目? And how to remove it? 以及如何将其删除?

This would happen if your text file has a trailing new line character, which is common. 如果您的文本文件具有尾随的换行符(这很常见),则会发生这种情况。

Why not trim before splitting? 为何在分割前不trim

enStrings = data.trim().split(/[\r\n]+/g);

Alternately, you could remove just the trailing new line characters before splitting. 或者,您可以在分割之前仅删除尾随的换行符。

enStrings = data.replace(/[\n\r]+$/, '').split(/[\r\n]+/g)

However, if your data is long, you may want to avoid the performance hit of recreating the entire string before splitting. 但是,如果数据很长,则可能要避免在拆分之前重新创建整个字符串的性能下降。 If that is the case, you could use the following to pop it off the end. 如果是这样,您可以使用以下命令将其弹出。

if (enStrings.length && !enStrings[enStrings.length-1]) {
    enStrings.pop();
}

You may use filter : 您可以使用filter

console.log(enStrings.filter(Boolean));

Empty strings are falsy value so using .filter(Boolean) will only list the truthy value and removes the empty strings from your array. 空字符串是虚假值,因此使用.filter(Boolean)将仅列出真实值并从数组中删除空字符串。

You can try this: 您可以尝试以下方法:

enStrings = data.split(/[\r\n]+/g);
enStrings.splice($.inArray('', enStrings), 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM