javascript - 如果条件警报,JS 会出现问题

标签 javascript

我是 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/

相关文章:

javascript - 如何在 Pycharm/Intellij 中打印到 javascript 控制台

javascript - 单击按钮时使用 jQuery 更改 CSS 定义

javascript - 为什么这个 jQuery .change 事件在 .click 事件后停止工作

javascript - Mongodb 更新过期

javascript - 基于 Typescript 的 React 组件的通用参数中的第二个参数代表什么?

javascript - D3 图表 Y 轴线在某些分辨率下不可见

javascript - 在Select2中,formatSelection和formatResult是如何工作的?

javascript - 在 IE 中 Javascript 的执行速度比 Firefox、Safari 和 Chrome 慢

javascript - 如何使用 Cloudfront 签名 URL 从生成的链接预览文件?

javascript - 为辅助函数减慢 Meteor 页面渲染速度