Reputation: 662
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?
Upvotes: 2
Views: 90
Reputation: 48417
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;
}));
Upvotes: 1
Reputation: 3087
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');
}
Upvotes: 3
Reputation: 41893
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();
Upvotes: 4
Reputation: 1774
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;
};
Upvotes: 1