-3

本质上,我想拥有它

if(condition) {"do this" || "do that"};

具体来说,我这样做是为了如果将特定 div 设置为特定颜色(从数组中随机选择),那么 4 个其他 div 中的 1 个会将其颜色更改为特定颜色。

谢谢!

编辑:我想我更想知道我是否可以随机化一个“then”语句。我正在制作一个游戏,所以我想避免选择我想获得新颜色的 4 个 div 中的哪一个(这意味着每个实例每次都编写相同的脚本)

4

2 回答 2

1

if 语句可以有很多次执行。随你喜欢。您可以做的是在该 if 语句中使用多个 if 来选择正确的 div 或使用 switch 代替。例如:

var array = [3, 4, 1, 2];

注意 有时我所做的是在随机挑选之前对混合索引的数组进行洗牌

var my_array = array.sort(); // This will change your array, for example, from [3, 4, 1, 2] to [1, 2, 3, 4].
or 
var my_array = array.reverse(); // This will change your array, for example, from [3, 4, 1, 2] to [4, 3, 2, 1].

var random_condition = Math.floor((Math.random() * 3)); // select at random from 0 to 3 because the array is ZERO based

然后你做你的logc:

if(condition) {
    if (random_condition == 1 ) {
        "do this" with div 1 // array [0] == 1
    }
    else if (random_condition == 2 ) {
        "do this" with div 2 // array [1] == 2
    }
    else if (random_condition == 3 ) {
        "do that" with div 3 // array [2] == 3
    }
    else if (random_condition == 4 ) {
        "do that" with div 4 // array [3] == 4
    }
}

或者使用开关

if(condition) {
    switch (random_condition) {
        CASE '1':
            "do this" with div 1 // array [0] == 1
            break;
        CASE '2':
            "do this" with div 2 // array [1] == 2
            break;
        CASE '3':
            "do this" with div 3 // array [2] == 3
            break;
        CASE '':
            "do this" with div 4 // array [3] == 4
            break;
        default
            // do nothing
            break;
    }
}
于 2017-04-24T14:24:17.020 回答
0

可以在一个块中做几件事(由{and包围}),但很简单

if(condition) {
 console.log("either do this"); 
 console.log("and do that");
} else {
 console.log("or do this"); 
 console.log("and this as well");
}

或'||' 例如,在 javascript 中不使用 shell 脚本。

else 部分可以再次拆分,例如

if (c1) {
} elseif (c2) {
} else {
}

如果您可以根据自己喜欢的条件重复此操作。

你也可以骰子:

function dice() {
    return Math.floor(Math.random() * 6 + 1);
}

然后对具有正确数字的元素做某事:

getElementById("div"+dice()).innerHtml = "changed";
于 2017-04-24T14:26:50.023 回答