如果条件警报,JS问题

时间:2017-06-14 05:29:56

标签: javascript

我是javascript的新手并试图运行js文件。我的问题是我试图在var“luckyplace”中保存randomItem()返回值并检查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.");
}

提前致谢...

1 个答案:

答案 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.");
}