2017-04-24 366 views
-3

從本質上講,我想把它使得if語句可以有多個執行嗎?

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

具體而言,我有它,以便如果一個特定的div被設置爲特定的顏色(隨機地從一個陣列拾取),然後4其他1 divs將其顏色更改爲特定顏色。

謝謝!

編輯: 我想我更想知道我是否可以隨機化一個'then'語句。我正在做一個遊戲,所以我想避免選擇我想要獲得新顏色的4個div中的哪一個(這意味着每個實例每次都腳本化)

+0

什麼''||實際上在這方面的意思? –

+0

你可以在if語句中使用if/else –

+0

那麼,這個僞代碼是什麼意思:「如果條件那麼做這個或做那個」?計算機如何知道什麼時候該做「這個」,什麼時候該做「那個」?解決問題的辦法:使用多個if語句,每個特定條件一個,或使用else語句。 – Jesper

回答

1

可以有很多執行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; 
    } 
} 
+0

我想我更想知道如果我可以隨機化一個'然後'的聲明。我正在做一個遊戲,所以我想避免選擇我想要獲得新顏色的4個div中的哪一個(這意味着每個實例每次都腳本化) – pacduck

+0

我使用隨機選取的方法更新了anser array – CAllen

+0

謝謝,這似乎是我需要的!一旦我有機會實施它,我會回來! – pacduck

0

能夠做幾件事情在一個塊(由{}包圍),而是簡單地

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"; 
+0

我想我更想知道我是否可以隨機化一個'then'語句。我正在做一個遊戲,所以我想避免選擇我想要獲得新顏色的4個div中的哪一個(這意味着每個實例每次都腳本化) – pacduck

+0

尋找'random'(例如https:// www.w3schools.com/jsref/jsref_random.asp),然後進行不同的任務,或者只是將隨機函數的可能結果命名爲目標。 – vv01f