为什么用逗号分隔的字符串不能在javaScript中使用split()转换为数组?

时间:2021-05-02 00:15:40

I am trying to convert a comma separated string into an array using the split method(Convert comma separated string to array).

我正在尝试使用split方法将逗号分隔的字符串转换为数组(将逗号分隔的字符串转换为数组)。

This is the code:

这是代码:

var nameList = "milk,sugar,flour";
var nameArray = nameList.split(',');

document.write('The nameList is: ' + nameList);
document.write('<br />');
document.write('The nameArray is: ' + nameArray);

This is the output:

这是输出:

The nameList is: milk,sugar,flour
The nameArray is: milk,sugar,flour

名字是:牛奶,糖,面粉名字是:牛奶,糖,面粉

It looks to me like it is still a string separated by commas. Why is the comma-separated string not converting to an array using split() in javaScript?

在我看来,它仍然是由逗号分隔的字符串。为什么用逗号分隔的字符串不能在javaScript中使用split()转换为数组?

3 个解决方案

#1


6  

It's an array. Array#toString produces the comma-separated output.

这是一个数组。数组#toString生成逗号分隔的输出。

Try this:

试试这个:

[3, 4, 'b'].toString(); 

If you use console.log instead of document.write to inspect nameArray, you'll see that it is an array.

如果你使用控制台。日志,而不是文档。写来检查nameArray,你会看到它是一个数组。

#2


0  

thats the way how JAVASCRIPT shoes an array

这就是JAVASCRIPT构建数组的方式

it did convert it

它把它

but you told JS to display it

但是你让JS显示它

so thats what he does.

他就是这么做的。

proof:

证明:

nameArray[0]====>milk

nameArray[1]====>sugar

#3


0  

When you implicitly convert the array to a string by appending it to a string, it displays the array.toString() which uses commas. You can override this if you want.

当您通过将数组附加到字符串隐式地将数组转换为字符串时,它将显示使用逗号的array. tostring()。如果需要的话,可以重写它。

if you do this instead, it will show the properly annotated version.

如果您这样做,它将显示适当注释的版本。

 JSON.stringify( nameArray ,"\t")

#1


6  

It's an array. Array#toString produces the comma-separated output.

这是一个数组。数组#toString生成逗号分隔的输出。

Try this:

试试这个:

[3, 4, 'b'].toString(); 

If you use console.log instead of document.write to inspect nameArray, you'll see that it is an array.

如果你使用控制台。日志,而不是文档。写来检查nameArray,你会看到它是一个数组。

#2


0  

thats the way how JAVASCRIPT shoes an array

这就是JAVASCRIPT构建数组的方式

it did convert it

它把它

but you told JS to display it

但是你让JS显示它

so thats what he does.

他就是这么做的。

proof:

证明:

nameArray[0]====>milk

nameArray[1]====>sugar

#3


0  

When you implicitly convert the array to a string by appending it to a string, it displays the array.toString() which uses commas. You can override this if you want.

当您通过将数组附加到字符串隐式地将数组转换为字符串时,它将显示使用逗号的array. tostring()。如果需要的话,可以重写它。

if you do this instead, it will show the properly annotated version.

如果您这样做,它将显示适当注释的版本。

 JSON.stringify( nameArray ,"\t")