简体   繁体   中英

How to check the values of an array full of Jquery objects

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!

WIN_COMBINATIONS.forEach(function(combination){
    if(combination.map(function(){return $(this).text()}).toArray().join("") == "XXX") { 
        console.log("winning combination")   
    } 
})   

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

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