初学者的问题,很抱歉,如果不是合适的地方
试图了解逻辑在JS
中的工作原理,无法弄清楚
if (firstSymbol === "A" || "a" || "D" || "d") {
if (secondSymbol === "z") {
alert("It does!");
break;
}
}
我希望它说“确实如此!”并在firstSymbol
是A,a,D或d并且secondSymbol
是z的情况下中断,但是由于某种原因,它说“它确实是!”。并且不管firstSymbol
是什么而中断,并且仅检查secondSymbol
是否为z。
答案 0 :(得分:2)
因为您要检查"a"
是否为真-它始终为真:
console.log(!!"a");
在这种情况下,您应该使用includes
和AND &&
const firstSymbol = "D";
const secondSymbol = "z";
if (["A", "a", "D", "d"].includes(firstSymbol) && secondSymbol == "z") {
console.log("It does!");
}
答案 1 :(得分:1)
function matchSecondSymbol(firstSymbol, secondSymbol) {
// By making FirstSymbol Uppercase, we can remove the other two conditions
firstSymbol = firstSymbol.toUpperCase();
if (['A', 'D'].includes(firstSymbol) && secondSymbol === "z") {
console.log('it Does');
}
else {
console.log('it does not');
}
}
matchSecondSymbol('a', 'z');
matchSecondSymbol('z', 'z');
matchSecondSymbol('a', 'y');
答案 2 :(得分:1)
在Javascript中,有一个称为truthy
和falsy
的值。总之,是在布尔(true
或false
)上下文中值的求值方式。
所有值都是真实的,除非将它们定义为虚假(即,除了false,0,“”,null,undefined和NaN之外)。
在您的代码中,编写时:
if (firstSymbol === "A" || "a" || "D" || "d")
您正在检查4个布尔条件:
firstSymbol === "A"
-结果将取决于firstSymbol
"a"
-始终评估为true
"D"
-始终评估为true
"d"
-始终评估为true
因此,由于条件2、3和4始终为true
,因此您的代码将始终输入if
语句。如果其中只有一个true
,其行为将是相同的。
您可以通过以下方式重写它:
if (firstSymbol === "A" || firstSymbol === "a" || firstSymbol === "D" || firstSymbol === "d")
或
if (["A", "a", "D", "d"].indexOf(firstSymbol) > -1)
或
if (["A", "D"].indexOf(firstSymbol.toUpperCase()) > -1)
答案 3 :(得分:0)
只需在样板中添加一些内容,这些示例便可以帮助您完成您想做的事情,并提供大量的可能性。
涵盖的测试
array.includes
array.indexOf
array.find
array.some
为什么您的代码无效?
之所以无效,是因为javascript计算了以下表达式:"A" || "a" || "D" || "d"
至"A"
,因为“ A”是 truthy 。如果需要与多个值进行比较,请使用一个数组,或者为每个值编写条件:
firstSymbol === "A" || firstSymbol === "D" ||...
上述示例:
/* Original code */
/*
if (firstSymbol === "A" || "a" || "D" || "d") {if (secondSymbol === "z") alert("It does!"); break;}
*/
let firstSymbol = "d", secondSymbol = "z";
// Using .includes
if (["A","a","D","d"].includes(firstSymbol) && secondSymbol === "z") console.log('it does, with .includes');
// Cleverer .includes due to the nature of the input.
if (["a","d"].includes(firstSymbol.toLowerCase()) && secondSymbol === "z") console.log('it does, with cleverer .includes');
// Using .indexOf
if (["A","a","D","d"].indexOf(firstSymbol) > -1 && secondSymbol === "z") console.log('it does, with .indexOf');
// Using .find
if (["A","a","D","d"].find(i => i === firstSymbol) && secondSymbol === "z") console.log('it does, with .find');
// Using. some
if (["A","a","D","d"].some(i => i === firstSymbol) && secondSymbol === "z") console.log('it does, with .some');
答案 4 :(得分:0)
在每种编程语言中,符号都是按照其优先顺序进行处理的。
其他人已经解释过,您的作业
firstSymbol === "A" || "a" || "D" || "d"
将被处理为
(firstSymbol === "A") || ("a") || ("D") || ("d")
链接到如何处理逻辑运算符:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence