0

我正在创建一个蹩脚的基于文本的游戏,我希望每个盒子上都没有玩家、怪物或健康包。我有一个像这样的对象数组:

var squares = [

    square1 = { //each square with its own number
        player:false,
        monster:false,
        healthPack:false
    },

    square2 = {
        player:false,
        monster:false,
        healthPack:false
    }

];

如果其中任何一个在广场上,我将其更改为真,我想知道如何检查是否有任何一个已经为真。

这就是我想知道的:

for ( var i in sqaures[x] ) {
     if( what do i put here??? == true ) return;
}

或者是否有另一种预先编写的方式?

4

3 回答 3

0

也许像这样的辅助函数。

Javascript

function isSquareTrue(square) {
    var i;

    for (i in square) {
        if (square.hasOwnProperty(i) && square[i]) {
            return true;
        }
    }

    return false;
}

var squareXX = { //each square with its own number
    player: false,
    monster: false,
    healthPack: false
}

console.log(isSquareTrue(squareXX));

jsfiddle

更新:对于演示数组中正方形的更改问题

Javascript

function anySquaresTrue(arrayOfSquares) {
    var length,
        index,
        property,
        square;

    for (index = 0, length = arrayOfSquares.length; index < length; index += 1) {
        square = arrayOfSquares[index];
        for (property in square) {
            if (square.hasOwnProperty(property) && square[property]) {
                return true;
            }
        }
    }

    return false;
}

var squares = [{ //each square with its own number
        player: false,
        monster: false,
        healthPack: false
    }, {
        player: false,
        monster: false,
        healthPack: false
    }];

console.log(anySquaresTrue(squares));

jsfiddle

于 2013-08-29T22:25:20.827 回答
0
    var squareXX = { //each square with its own number
    player:false,
    monster:false,
    healthPack:true
    }
    for (key in squareXX) {
      if (squareXX[key] == true){
      alert("true is a " + key);
      }
    }

试试这个代码。应该 alert true 是一个 healthPack。

于 2013-08-29T22:25:21.810 回答
-1

你是说这个吗?

if ((player) || (monster) || (healthPack)) {...
于 2013-08-29T22:21:53.530 回答