2012-10-13 49 views
2

学习JavaScript时,我没有明白为什么打印返回的Sting.split()方法(使用正则表达式作为参数)的数组时输出的原因如下。javascript split()数组包含

var colorString = "red,blue,green,yellow"; 
var colors = colorString.split(/[^\,]+/); 
document.write(colors); //this print 7 times comma: ,,,,,,, 

然而,当我打印阵列颜色的单个元素,它打印一个空字符串,三个逗号和一个空字符串:

document.write(colors[0]); //empty string 
document.write(colors[1]); //, 
document.write(colors[2]); //, 
document.write(colors[3]); //, 
document.write(colors[4]); //empty string 
document.write(colors[5]); //undefined 
document.write(colors[6]); //undefined 

那么,为什么打印阵列直接给出7个逗号。

虽然我认为在第二个输出中有三个逗号是正确的,但我没有明白为什么有一个开始(在索引0处)和结束空字符串(在索引4处)。

请解释我在这里搞砸了。

回答

8

/[^\,]+/将一个或多个字符分割为而不是逗号。因此,JavaScript会将您的字符串分割为red,blue等。所得到的剩余部分是开头处的空字符串(索引0到0的子字符串),逗号和末尾的空字符串。如果你超出数组范围,你会得到undefined(与任何数组一样)。

red,blue,green,yellow 
xxx xxxx xxxxx xxxxxx <-- x is what is being eaten during split, because it's the delimiter 

你只是想.split(","),其将在逗号,让逗号被吃掉,你会留下颜色。

现在,当你做document.write(someArray)时,数组被转换成一个字符串,以便它可以被显示。这实际上意味着调用someArray.join(),默认情况下会在两者之间插入逗号。所以你可以用逗号加逗号,从而得到更多的逗号。

5

当您打印出数组时,数组的不同元素也用逗号分隔。所以你的输出是这5个数组元素:

[empty string],[comma],[comma],[comma],[empty string] 

总计7个逗号。为什么你得到逗号和空字符串而不是颜色的原因是,split将在所有匹配的内容中分割(而不是将所有匹配的内容都还给你)。所以根本不使用正则表达式在所有的,只是在拆,

var colors = colorString.split(','); 
2

[^ \] < - 这意味着什么逗号。

尝试 var colors = colorString.split(',');