在Javascript中为对象属性赋予随机属性值

时间:2018-12-03 19:53:24

标签: javascript

我正在尝试创建一个基于图块的游戏,并希望为每种类型的图块赋予随机颜色,例如:

Game.Glyph = function(properties) {
    properties = properties || {};
    this._char = properties['character'] || ' ';
    this._foreground = properties['foreground'] || 'white';
};

Game.Tile.floorTile = new Game.Tile({
    character: '.',
});

然后假设我已经在map中填充了Game.Tile.floorTile数组

for (let x = 0; x < this._width; x++) {
            for (let y = 0; y < this._height; y++) {
                if (map[x][y] == Game.Tile.floorTile) {
                    map[x][y]._foreground = ['red','yellow'].random();
            }

     }
}

这将导致每个地砖为红色或黄色,而不是随机分布。如何像上面尝试的那样给每个拼贴提供随机的颜色?

1 个答案:

答案 0 :(得分:2)

如果只想在两个值之间进行选择,则ternary可以与Math.random()结合使用,从而产生一个介于0和1之间的值。

map[x][y]._foreground = Math.random() > 0.5 ? 'red': 'yellow'

例如,使用简化的代码:

let map = [[{}, {}],[{}, {}]]

for (let x = 0; x < 2; x++) {
    for (let y = 0; y < 2; y++) {
            map[x][y]._foreground = Math.random() > 0.5 ? 'red': 'yellow'
    }

}
console.log(map)