简体   繁体   中英

How can I shorten this JavaScript if statement?

I want check if all elements of an array are different from undefined. array_main contains 9 elements.

I've created an if as below:

// Function checking is there a tie - 0:0
var check_if_tie = function () {
    if( array_main[0] !== undefined && array_main[1] !== undefined && 
        array_main[2] !== undefined && array_main[3] !== undefined && 
        array_main[4] !== undefined && array_main[5] !== undefined && 
        array_main[6] !== undefined && array_main[7] !== undefined && 
        array_main[8] !== undefined ) {
        alert("TIE!/REMIS!");
        return false;
    } else {
        console.log('Continue playing');
        return false;
    }
};

Is it possible to shorten this if somehow?

Assuming that you want to iterate over every element from the array_main array, you can use Array#every .

It will return true if every element from the given array fulfills the !== undefined condition. If at least one element doesn't pass it, it will return false .

 var array_main = [1,2,3]; var check_if_tie = function() { if (array_main.every(v => v !== undefined)) { alert("TIE!/REMIS!"); return false; } else { console.log('Continue playing'); return false; } } check_if_tie(); 

There are a number of way you can do this.One of then is checking the index of undefined.

 var array_main= [1,3,4,54,5,undefined,4,54] if(array_main.indexOf(undefined) > -1) { alert("TIE!/REMIS!"); } else { console.log('Continue playing'); } 

You can use every method which accepts a callback method.

array_main.every(function(item){
    return item != undefined;
});

You can also use arrow functions accepted by ES6 .

array_main.every(item => item!=undefined);

Here is a short example:

 var array_main = new Array(9).fill(undefined); console.log(array_main.every(function(item){ return item != undefined; })); 

var check_if_tie = function(){
    for(elem in array_main)
    {
        if(array_main[elem] == undefined)
        {
            alert("TIE!/REMIS!");
            return false;
        }   
    }
    console.log("Continue playing");
    return false;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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