JavaScriptを学習しているときに、Sting.split()メソッドから返された配列(正規表現を引数として)を出力したときの出力が以下のようになる理由がわかりませんでした。
var colorString = "red,blue,green,yellow";
var colors = colorString.split(/[^\,]+/);
document.write(colors); //this print 7 times comma: ,,,,,,,
ただし、配列の色の個々の要素を出力すると、空の文字列、3つのコンマ、および空の文字列が出力されます。
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つのコンマが表示されるのはなぜですか。
2番目の出力に3つのコンマがあるのは正しいと思いますが、開始(インデックス0)と終了の空の文字列(インデックス4)がある理由がわかりませんでした。
私がここでめちゃくちゃになっていることを説明してください。