2017-06-14 44 views
0

我是JavaScript的新手,並試圖運行js文件。我的問題是我試圖在var「luckyplace」中保存randomItem()返回值並檢查if-else條件。當我運行該文件時,它沒有給出任何條件警報,我也沒有看到任何錯誤。請幫忙 !與JS問題,如果條件警報

/*jslint devel: true */ 
 
alert("You are away from home long time, and you forgot where you kept the key. You have to search few places to find the key and get in !"); 
 

 
var places = ["flower pot", "under mat", "side of window", "top of front door"]; 
 
alert("place you can search are listed below:" + " " + places); 
 

 
function randomItem(range) { 
 
    "use strict"; 
 
    return Math.round(Math.random() * range); 
 
} 
 
alert(places[randomItem(places.length - 1)]); 
 

 
var luckyplace = randomItem(); 
 

 
if (luckyplace === "flower pot") { 
 
    alert("No key, no flowers !"); 
 
} else if (randomItem() === "under mat") { 
 
    alert("Try somewhere else."); 
 
} else if (randomItem() === "side of window") { 
 
    alert("you are not lucky enough"); 
 
} else if (randomItem() === "top of front door") { 
 
    alert("great ! you found the key. Unlock the door."); 
 
}

在此先感謝...

+0

你隨機項函數返回數組 –

回答

1

你打電話randomItem幾次,所有但你忘了在長傳,然後查找第一次places數組中的項目。看看我的編輯如下;我不是100%確定你想要什麼,但希望它能指引你朝着正確的方向前進。

/*jslint devel: true */ 
 
alert("You are away from home long time, and you forgot where you kept the key. You have to search few places to find the key and get in !"); 
 

 
var places = ["flower pot", "under mat", "side of window", "top of front door"]; 
 
alert("place you can search are listed below:" + " " + places); 
 

 
function randomItem(range) { 
 
    "use strict"; 
 
    return Math.floor(Math.random() * range); 
 
} 
 
var luckyplace = places[randomItem(places.length)]; 
 

 
alert(luckyplace); 
 

 
if (luckyplace === "flower pot") { 
 
    alert("No key, no flowers !"); 
 
} else if (luckyplace === "under mat") { 
 
    alert("Try somewhere else."); 
 
} else if (luckyplace === "side of window") { 
 
    alert("you are not lucky enough"); 
 
} else if (luckyplace === "top of front door") { 
 
    alert("great ! you found the key. Unlock the door."); 
 
}

+1

燁隨機指標,而不是一個項目,只需編輯這些呢。謝謝。 – smarx

+0

我建議使用開關而不是'if ... elseif'階梯。同樣使用'Math.floor'將確保索引永遠不會超出範圍。 – Rajesh

+0

@smarx,感謝您的幫助,是的它的工作。 – Arun