很抱歉,如果我在写这篇文章时犯了错误。我是新来的,不知道这是如何工作的,希望我能尽快学会。我也是 JavaScript 新手。
所以问题是:我的 code.elements.js 文件中有这个,但我无法让它工作。
放置这个有用吗?
if (codePrompt == (codeSwitch || codeSwitchBG || codeBlur || codeShowInfo)){};
或者我必须通过正常方式做到这一点?,比如
if (codePrompt == codeSwitch || codePrompt == codeSwitchBG || codePrompt == codeBlur || codePrompt == codeShowInfo){};
var codeSwitch = 'switch()';
var codeSwitchBG = 'switch(background)';
var codeBlur = 'blur()';
var codeShowInfo = 'showInfo()';
$(".code").on("click", function () {
var codePrompt = prompt("Set the code in the command line.");
if (codePrompt == (codeSwitch || codeSwitchBG || codeBlur || codeShowInfo)) {
if (codePrompt == codeSwitch) {
alert("Switching background...");
console.log("Used '" + codeSwitch + "' command.");
} else if(codePrompt == codeBlur) {
alert("Blurring elements...");
console.log("Used '" + codeBlur + "' command.");
} else if(codePrompt == codeSwitchBG) {
alert("Switching background...");
console.log("Used '"+ codeSwitchBG + "' command.");
}else if(codePrompt == codeShowInfo) {
alert("Showing info...");
console.log("Used '"+ codeShowInfo + "' command.");
}
} else {
alert("Wrong command, try again.");
console.log("Wrong command, try again.");
};
});
最佳答案
“正常”方式按照您可能期望的方式工作。
但是,无论如何,if 语句是多余的。您可以跳过它:
if (codePrompt === codeSwitch) {
alert("Switching background...");
console.log("Used '" + codeSwitch + "' command.");
} else if (codePrompt === codeBlur) {
alert("Blurring elements...");
console.log("Used '" + codeBlur + "' command.");
} else if (codePrompt === codeSwitchBG) {
alert("Switching background...");
console.log("Used '" + codeSwitchBG + "' command.");
} else if (codePrompt === codeShowInfo) {
alert("Showing info...");
console.log("Used '" + codeShowInfo + "' command.");
} else {
alert("Wrong command, try again.");
console.log("Wrong command, try again.");
}
这是一个很好的switch 用例
,我会这样重构它:
var alertMessage = "",
consoleMessage = "Used '" + codePrompt + "' command.";
switch (codePrompt) {
case codeSwitch:
alertMessage = "Switching background...";
break;
case codeBlur:
alertMessage = "Blurring elements...";
break;
case codeSwitchBG:
alertMessage = "Switching background...";
break;
case codeShowInfo:
alertMessage = "Showing info...";
break;
default:
alertMessage = consoleMessage = "Wrong command, try again.";
break;
}
alert(alertMessage);
console.log(consoleMessage);
关于Javascript:如何简化具有多个 OR 条件的 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23959932/