Question

new to Javascript and trying to make a little thing that will let me decide what movie I'm going to watch. 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);
Was it helpful?

Solution

The select variable returns as a string. 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.

OTHER TIPS

if( select === 1) always false because select will return as string.... instead of select === 1 use select === "1" or select == 1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top