[英]The different between if statement and ternary operator
function findBiggestFraction( a , b ) { a > b ? console.log("a: ", a): ("b: ", b); } var firstFraction = 3/4; var secondFraction = 5/7; findBiggestFraction(firstFraction, secondFraction); // a: 0.75 findBiggestFraction(7/16, 13/25); // b: 0.52 findBiggestFraction(1/2, 3/4); // a: 0.75 function findBiggestFraction( a , b ) { if (a > b) { console.log("a: ", a); } else { console.log("b: ", b); } } var firstFraction = 3/4; var secondFraction = 5/7; findBiggestFraction(firstFraction, secondFraction); // a: 0.75 findBiggestFraction(7/16, 13/25); // b: 0.52 findBiggestFraction(1/2, 3/4); // a: 0.75
when I run the first code block it only execute the first call. 当我运行第一个代码块时,它仅执行第一个调用。 On the other hand for the second block, it runs all three. 另一方面,对于第二个块,它将运行所有三个块。
您缺少b的console.log
。
a > b ? console.log("a: ", a): console.log("b: ", b);
With the ternary, you're never calling console.log
when the condition is false. 对于三元组,当条件为false时,您永远不会调用console.log
。 ("b: ", b)
evaluates to b
, then you don't do anything with the result. ("b: ", b)
为b
,那么您对该结果不做任何事情。
Roughly equivalent code using an if-statement would be 使用if语句的大致等效代码为
if (a > b) {
console.log("a: ", a);
} else {
("b: ", b);
}
The mistake is arguably much clearer when you use the more verbose statement. 当您使用更冗长的语句时,该错误可以说更清楚。 Change the ternary line to 将三元线更改为
a > b ? console.log("a: ", a) : console.log("b: ", b);
Note that using a ternary to run side effects is generally regarded as bad practice. 注意,使用三元来产生副作用通常被认为是不好的做法。 Either use the ternary inside of console.log
to pick what argument to pass in, or use an if-statement. 使用console.log
内部的三进制选择要传入的参数,或者使用if语句。
You're functions are not the same. 您的功能不一样。 The first function only prints something if a > b
is true. 如果a > b
为true,则第一个函数仅打印某些内容。 The second function prints either way. 第二个函数以两种方式打印。
This is a caveat to using the ternary operator. 这是使用三元运算符的警告。 It's very helpful, but can be easy to miss details like you just did. 这非常有帮助,但是像您刚才那样容易遗漏细节。
Summary: Both blocks run both functions, but the first block only prints ~half the time. 简介:两个模块都运行这两个功能,但是第一个模块仅打印大约一半的时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.