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

exports.test = function(rq, rs){

   var mailList = "[email protected],[email protected]";
   var arrayList = mailList.split(",");
   console.log(mailList + " array lenght " + arrayList.length );

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

   mailList = "[email protected],";
   console.log(mailList + " array lenght " + arrayList.length );

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

   rs.send("test here ");

}


控制台输出为:

[email protected],[email protected] array lenght 2
array lenght 1
[email protected], array lenght 1
, array lenght 1


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

最佳答案

第一次比赛之前的所有内容都将作为第一个元素返回。即使字符串为空。不为空

如果要拆分并返回长度为0的数组,我建议您使用underscore.string modulewords方法:

_str.words("", ",");
// => []

_str.words("Foo", ",");
// => [ 'Foo' ]

07-24 18:00