学习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处)。
请解释我在这里搞砸了。