Reputation:
I'm writing a simple tic tac toe game, and I'm trying to check for different win states. The different tiles are set up in an array, so to check for a win for the three top spaces I have
if (tableArr[0].hasClass('userTaken') && tableArr[1].hasClass('userTaken') && tableArr[2].hasClass('userTaken')){
select(); //ends game
}
I'm looking for a way to shorten this, I tried tableArr[0,1,2].hasClass('userTaken')
but that didn't work. Any suggestions?
Upvotes: 0
Views: 209
Reputation: 3683
Also you could check if some element doesn't have the class with some :
tableArr.slice(0, 3).some(x => !x.hasClass('userTaken'))
Upvotes: 0
Reputation: 9642
You could potentially use every
for this, but you'd also need to slice the array too. As an example:
tableArr.slice(0, 3).every(x => x.hasClass('userTaken'))
So, take the first three elements of the array using slice
, then every
checks that the test passes for each of them.
Of course, if this is tic, tac, toe, you'll need to check diagonals too, which is trickier using .slice
. You could use map
for this too, e.g.
[0,1,2].map(idx => tableArr[idx]).every(x => x.hasClass('userTaken'))
Upvotes: 3