JavaScript split 为空字符串赋予数组大小 1,而不是 0

标签 javascript node.js split

我想用逗号分割字符串以获取 Node.js 中的数组。

exports.test = function(rq, rs){

   var mailList = "sharan@test.com,pradeep@test.com";
   var arrayList = mailList.split(",");    
   console.log(mailList + " array lenght " + arrayList.length );

   mailList = "";
   arrayList = mailList.split(",");
   console.log(mailList + " array lenght " + arrayList.length );

   mailList = "sharan@test.com,";
   console.log(mailList + " array lenght " + arrayList.length );

   mailList = ",";
   console.log(mailList + " array lenght " + arrayList.length );

   rs.send("test here ");

}

控制台输出为:

sharan@test.com,pradeep@test.com array lenght 2
array lenght 1
sharan@test.com, array lenght 1
, array lenght 1

为什么 JavaScript "".split() 返回一个只有一个元素的数组而不是空数组?

最佳答案

返回的数组包含一个空字符串 ([""])。它以这种方式工作,因为直到第一个匹配项(或字符串末尾)为止的所有内容都作为数组的第一个元素返回。在空字符串的情况下,这是一个空字符串。

如果您考虑一下分割算法的实现可能是什么样子,这是有道理的。可能您从包含当前元素的空字符串开始,然后循环遍历字符串的字母,将它们添加到当前元素,直到到达字符串或分隔符的末尾。然后将当前元素插入结果数组。

如果字符串长度为零,则当前元素将从空字符串开始。您直接到达末尾,因此将空字符串推送到结果数组并返回它。

这也是它应该如何工作的。来自 ECMAScript Language Specification :

If the this object is (or converts to) the empty String, the result depends on whether separator can match the empty String. If it can, the result array contains no elements. Otherwise, the result array contains one element, which is the empty String.

来自 Mozilla :

When found, separator is removed from the string and the substrings are returned in an array. If separator is not found or is omitted, the array contains one element consisting of the entire string.

Note: When the string is empty, split() returns an array containing one empty string, rather than an empty array.

如果您不喜欢这种行为,您可以编写自己的版本:

//Return an empty array if string is empty.
//Otherwise return the result of the ordinary split.
split2 = (separator) => this == "" ? [] : this.split(separator);

关于JavaScript split 为空字符串赋予数组大小 1,而不是 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33516370/

相关文章:

ruby-on-rails - 如何使用第一个逗号将字符串拆分成段落?

Python Split() 和 re.split()

string - 在 Pandas 中将一列拆分为 3 列

node.js - nodemon 无法正常工作

xml - 尝试从 Node.js 获取信息 SOAP 时出错

javascript - 如何保护数组不被刷新

javascript - 如果使用 css "calc"则 map 不显示

node.js - 使用中间件在expressjs中的应用程序重定向

javascript - 允许使用 bootstrap-datepicker 进行 1 天预订

javascript - slim 3 : Event Handling not Working as Expected