简体   繁体   English

使用拼接时,项目无法从数组中正确删除

[英]Items not deleting properly from array when using splice

new to Javascript and trying to make a little thing that will let me decide what movie I'm going to watch. Javascript的新手,并试图制作一个小东西,让我决定我要观看哪部电影。 I've made a test list of some movies. 我制作了一些电影的测试清单。 Then I'm shown two movies at a time from the list, and each time I have to veto one of the movies. 然后我从列表中一次显示两部电影,每次我都要否决其中一部电影。 This should continue until there's only one movie left, at which point a pop-up will tell me what movie to watch. 这应该会继续,直到只剩下一部电影,此时弹出窗口会告诉我要观看哪部电影。

The problem is, it's not working properly. 问题是,它无法正常工作。 It doesn't seem to delete the last item on my list no matter what I do, and sometimes movies do not delete at all. 无论我做什么,它似乎都不会删除我列表中的最后一项,有时电影根本不删除。 Here is the code I'm using. 这是我正在使用的代码。 Could someone help point me in the right direction? 有人能指点我正确的方向吗?

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);

The select variable returns as a string. select变量作为字符串返回。 Hence, 因此,

select === 1 // always false
select === '1' // works as expected

Modified Source: 修改来源:

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);

Also, use var to declare variables - always. 另外,使用var来声明变量 - 总是如此。

if(select === 1)总是为false因为select将返回为字符串....而不是select === 1使用select ===“1”或select == 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM