[英]Items not deleting properly from array when using splice
Javascript的新手,并试图制作一个小东西,让我决定我要观看哪部电影。 我制作了一些电影的测试清单。 然后我从列表中一次显示两部电影,每次我都要否决其中一部电影。 这应该会继续,直到只剩下一部电影,此时弹出窗口会告诉我要观看哪部电影。
问题是,它无法正常工作。 无论我做什么,它似乎都不会删除我列表中的最后一项,有时电影根本不删除。 这是我正在使用的代码。 有人能指点我正确的方向吗?
var options = [
"ET",
"Schindler’s List",
"Up",
"What’s Eating Gilbert Grape",
];
var process = function() {
while (options.length > 1) {
for (i = options.length-1; i >= 1; i--) {
var select = prompt("VETO one of the following: 1. " + options[i] + " 2. " + options[i-1]);
if (select === 1) {
options.splice(i, 1);
}
else {
options.splice(i-1, 1);
}
}
}
};
process();
alert(options);
select变量作为字符串返回。 因此,
select === 1 // always false
select === '1' // works as expected
修改来源:
var options = [
"ET",
"Schindler’s List",
"Up",
"What’s Eating Gilbert Grape",
];
var process = function() {
while (options.length > 1) {
for (var i = options.length-1; i >= 1; i--) {
var select = prompt("VETO one of the following: 1. " + options[i] + " 2. " + options[i-1]);
if (select === '1') { // changed
options.splice(i, 1);
}
else {
options.splice(i-1, 1);
}
}
}
};
process();
alert(options);
另外,使用var
来声明变量 - 总是如此。
if(select === 1)总是为false因为select将返回为字符串....而不是select === 1使用select ===“1”或select == 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.