多维数组 - 测试嵌套数组中的所有值是否相等

时间:2014-01-06 20:57:04

标签: javascript jquery arrays

所以,我有一个如下所示的数组:

[ ["","",""], ["","",""], ["","",""] ]

如何在javascript中测试它,看看1st index是否填充了X

EX: [ ["X","X","X"], ["","",""], ["","",""] ]

我一直在想我应该做这样的事情,但感觉会有更快的方式......

var counter = 0, 
    win,
    b = [ ["X","X","X"], ["","",""], ["","",""] ],
    num = b[0].length;
for(var i=0; i<num; i++){
    if(b[0][i]==="X"){ counter++; }
}
if(num===counter){ win=true; }

8 个答案:

答案 0 :(得分:2)

var win = b[0].join('') === 'XXX';

答案 1 :(得分:1)

win = true;
for (var i = 0; i < num; i++) {
    if (b[0][i] != "X") {
        win = false;
        break;
    }
}

答案 2 :(得分:1)

使用Array.prototype.everyhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

function isAnX(c) { return c === 'X'; }
var win = b[0].every(isAnX);

答案 3 :(得分:1)

以下是测试数组是否包含相同元素的方法:

allTheSame = someArray.every(function(x, _, ary) { return x == ary[0] })

请参阅every

或者,对于ES5之前的引擎:

allTheSame = function(ary) {
    for(var i = 1; i < ary.length; i++)
       if(ary[i] != ary[0]) return false;
    return true;
}

答案 4 :(得分:0)

使用Array.prototype.reduce

 var win=b[0].reduce(function (v, c) { return v && (c=="X") }, true); 

答案 5 :(得分:0)

另一个,只是再给一个选项:

var win = new RegExp("^X{"+b[0].length+"}$").test(b[0].join(''));

干杯

答案 6 :(得分:0)

与其他答案类似,但有一些扭曲:

var all = function(val, arr) {
    var fn = function(arr) {return arr.every(function(item) {return item === val;});};
    return arguments.length > 1 ? fn(arr) : fn;
};

var win = all('X', b[0]); //=> true
// or
var allXs = all('X');
var win = allXs(b[0]); //=> true

或者,如果您只是想知道它们是否完全相同:

var allAlike = function(arr) {
    return (arr.length == 0) || all(arr[0], arr);
}

var win = allAlike(b[0]);

如果您有适当的咖喱式功能,这会更容易。

答案 7 :(得分:0)

哈哈哈,这很酷:

var win = Array(b[0].length+1).join('X') == b[0].join('')

干杯!