JavaScript:拆分不一致

我在 JavaScript 中使用 split() 方法得到了一个非常令人困惑的结果。


var winning = "1234".split(" ");

var entry1 = "23".split(" ");

var entry2 = "123".split(" ");

var entry3 = "55".split(" ");

var entry4 = "8888".split(" ");

var entry5 = "21".split(" ");

var counter1, counter2, counter3, counter4, counter5;

counter1 = 3;

counter2 = 3;

counter3 = 3;

counter4 = 3;

counter5 = 3;

for(var i = entry1.length - 1; i >= 0; i--){

    console.log(winning[counter1] + "===" + entry1[i]);

    counter1 -= 1

}


for(var i = entry2.length - 1; i >= 0; i--){

    console.log(winning[counter2] + "===" + entry2[i]);

    counter2 -= 1

}


for(var i = entry3.length - 1; i >= 0; i--){

    console.log(winning[counter3] + "===" + entry3[i]);

    counter3 -= 1

}


for(var i = entry4.length - 1; i >= 0; i--){

    console.log(winning[counter4] + "===" + entry4[i]);

    counter4 -= 1

}


for(var i = entry5.length - 1; i >= 0; i--){

    console.log(winning[counter5] + "===" + entry5[i]);

    counter5 -= 1

}

当我运行这个简单的代码时,使用 split 获得的获胜数组在任何索引中均未定义,但 split 方法生成的其他数组似乎工作正常。只是为什么?这是什么矛盾?


慕斯王
浏览 80回答 1
1回答

弑天下

看这个:var winning = "1234".split(" ");var entry1 = "23".split(" ");var entry2 = "123".split(" ");var entry3 = "55".split(" ");var entry4 = "8888".split(" ");var entry5 = "21".split(" ");console.dir(winning)console.dir(entry1)console.dir(entry2)console.dir(entry3)console.dir(entry4)console.dir(entry5)数组中只有一个元素winning,因此当您尝试获取具有索引的元素时,3您会得到undefined. 其他数组也有一个元素 - 您循环遍历它们并打印该元素。我想你想这样做:var winning = "1234".split("");而不是这个:var winning = "1234".split(" ");因为这些字符串中没有空格字符。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript