Reputation: 65
I am making a tic-tac-toe game for fun and I am trying to do something a little different.
I am currently trying to check winning combinations by iterating through an array of stored tds that were grabbed with Jquery.
WIN_COMBINATIONS = [$("#square_0, #square_1, #square_2"),
$("#square_6, #square_7, #square_8"),
$("#square_0, #square_3, #square_6"),
$("#square_3, #square_4, #square_5"),
$("#square_1, #square_4, #square_7"),
$("#square_2, #square_5, #square_8"),
$("#square_0, #square_4, #square_8"), $("#square_6, #square_4, #square_2")]
So, basically, WIN_COMBINATIONS[0] is a winning combo. What is the best way to iterate through, and actually check the .html of the Jquery object?
Basically, I would like to do something like this
if (WIN_COMBINATIONS[0].html = "X", "X", "X") {
//do something here
}
Thanks for your help!
Upvotes: 0
Views: 34
Reputation: 949
if ES6 (ES2015) is OK than you can try reduce to find match
!!array.reduce(function(a, b){ return (a === b) ? a : NaN; });
Results:
var array = ["a", "a", "a"] => result: "true"
var array = ["a", "b", "a"] => result: "false"
var array = ["false", ""] => result: "false"
var array = ["false", false] => result: "false"
var array = ["false", "false"] => result: "true"
var array = [NaN, NaN] => result: "false"
Warning:
var array = [] => result: TypeError thrown
All credit to: Lightness Races in Orbit
Upvotes: 0
Reputation: 16068
WIN_COMBINATIONS.forEach(function(combination){
if(combination.map(function(){return $(this).text()}).toArray().join("") == "XXX") {
console.log("winning combination")
}
})
Upvotes: 2