我有以下代码,但我不明白为什么answer变量的结果是" 1234undefinedundefined" 。不应该是" 1234" ?
https://jsfiddle.net/JSmithd/t5roheuL/
var theanswer = "1,2,3,4";
var answerarray = theanswer.split(",");
var answer = "";
alert(theanswer.length);
for (z = 0; z < theanswer.length - 1; z++) {
if (answerarray[z] != "," && answerarray[z] != "undefined") {
answer = answer + answerarray[z];
}
}
alert(answer);
答案 0 :(得分:1)
你的for循环语句中的编码错误。
for (z = 0; z < theanswer.length - 1; z++)
theanswer.length == 7
因为它是一个包含7个字符的字符串
这应该是
for (z = 0; z < answerarray.length; z++)
answerarray.length == 4
因为它的ARRAY有4个元素。进行拆分后,将其转换为数组。