从本质上讲,我想把它使得if语句可以有多个执行吗?
if(condition) {"do this" || "do that"};
具体而言,我有它,以便如果一个特定的div被设置为特定的颜色(随机地从一个阵列拾取),然后4其他1 divs将其颜色更改为特定颜色。
谢谢!
编辑: 我想我更想知道我是否可以随机化一个'then'语句。我正在做一个游戏,所以我想避免选择我想要获得新颜色的4个div中的哪一个(这意味着每个实例每次都脚本化)
从本质上讲,我想把它使得if语句可以有多个执行吗?
if(condition) {"do this" || "do that"};
具体而言,我有它,以便如果一个特定的div被设置为特定的颜色(随机地从一个阵列拾取),然后4其他1 divs将其颜色更改为特定颜色。
谢谢!
编辑: 我想我更想知道我是否可以随机化一个'then'语句。我正在做一个游戏,所以我想避免选择我想要获得新颜色的4个div中的哪一个(这意味着每个实例每次都脚本化)
可以有很多执行if声明。尽可能多的你喜欢。 你可以做的是使用多个,如果在这一个if语句选择正确的div或使用开关来代替。例如:
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;
}
}
能够做几件事情在一个块(由{
和}
包围),而是简单地
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脚本。
其他部分可以再次分割,例如,
if (c1) {
} elseif (c2) {
} else {
}
这个elseif你可以重复你喜欢的条件。
你也可以骰子:
function dice() {
return Math.floor(Math.random() * 6 + 1);
}
,然后就去做某事物有正确数量的元素:
getElementById("div"+dice()).innerHtml = "changed";
什么''||实际上在这方面的意思? –
你可以在if语句中使用if/else –
那么,这个伪代码是什么意思:“如果条件那么做这个或做那个”?计算机如何知道什么时候该做“这个”,什么时候该做“那个”?解决问题的办法:使用多个if语句,每个特定条件一个,或使用else语句。 – Jesper