我是 javascript 新手,正在尝试运行 js 文件。我的问题是我试图将 randomItem() 返回值保存在 var "luckyplace"中并检查 if-else 条件。当我运行该文件时,它没有给我任何条件的任何警报,而且我也没有看到任何错误。请帮忙!
/*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.");
}
提前致谢...
最佳答案
您多次调用 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.");
}
关于javascript - 如果条件警报,JS 会出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44536135/