從本質上講,我想把它使得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