我在 jsfiddle.net 上玩,我很好奇为什么这会返回 true?
if(0 < 5 < 3) {
alert("True");
}
这也是:
if(0 < 5 < 2) {
alert("True");
}
但这不是:
if(0 < 5 < 1) {
alert("True");
}
这个怪癖有用吗?
操作顺序导致
(0 < 5 < 3)
在 javascript 中被解释为 ((0 < 5) < 3)
,从而生成 (true < 3)
,并且 true 被计为 1,导致其返回 true。
这也是为什么
(0 < 5 < 1)
返回 false,(0 < 5)
返回 true,被解释为 1
,导致 (1 < 1)
。
我的猜测是因为
0 < 5
是 true,并且 true < 3
被转换为 1 < 3
,这是 true。
可能是因为
true
被假定为 1
所以
0 < 5 < 3 --> true < 3 --> 1 < 3 --> true
因为
true < 3
,因为true == 1
关于你的问题这个怪癖是否有用:我想在某些情况下它可能会有用(如果压缩代码就是你所追求的),但依赖它(很可能)会严重降低你的代码的可理解性.
这有点像使用后/前增量/减量作为更大表达式的一部分。你能一眼看出这段代码的结果是什么吗?
int x = 5;
int result = ++x + x++ + --x;
注意:使用此代码,有时甚至可以根据语言和编译器得到不同的结果。
这是一个好主意,可以让自己和下一个会阅读你代码的人的生活变得轻松。清楚地写出您真正想要发生的事情,而不是依赖于布尔值的隐式转换等副作用。
然而,如果你有一个 1 为真、0 为假的心智模型,那么就会产生各种非常有用、强大且直接的不错的布尔技术。例如,您可以直接使用 A > 100 的结果来递增计数器,如果 A 大于 100,则计数器会递增。这种技术在 Java 中可能被视为一种怪癖或技巧,但在数组或函数式语言中可能是惯用语。
数组语言 APL 中的一个经典示例是计算数组中(例如)大于 100 的项目数:
+/A>100
如果 A 是 5 项数组 107 22 256 110 3 那么:
A>100
产生 5 项布尔数组:
1 0 1 1 0
并对这个布尔结果求和:
+/1 0 1 1 0
得出最终答案:
3
(0 < 5 < 3)
从左到右开始,因此它评估第一个 0
< 5. Is it true? Yes. Since TRUE=1, it evaluates 1 < 3. Since 1 is less than 3 so it's true.
现在有了这个
(0 < 5 < 1)
0 小于 5 吗?是的。因此,使其为 TRUE,这也意味着 1。现在考虑到这一事实,它的计算结果为 (1
< 1). Is 1 less than 1? No, therefore it's false. It has to be equal.
<5 which would return 1 for true when 1<3 which is true?
C#想让你做这个“操作符”<' cannot be applied to operands of type 'bool' and 'int'"
if(0 < 5 && 5 < 3) {
alert("True");}
这当然是错误的,因此您不会收到“真实”警报。 很高兴我读到了这篇文章,我现在知道为什么了。
3 < x < 10
将在 vanilla JS 中转换为
(3 < x && x < 10)
0 < 5 < 3
==> ( ( 0 < 5 ) < 3 )
==> true < 3
==> 1 < 3
==> true
true + 1 which gives you 2.
所以
0 < 5
,返回的布尔值(true)用数学运算符进行运算(
true
<) will return a number. So it boils to 1<3 which returns
2 > 1); // 假< 2 < 3); // true // Case 2 console.log(3 >
案例1: “1< 2" is true and "true < 3" is then coerced to "1 < 3" which is also true and thus the final output is true
案例2: “3>2”为真,但这里“true > 1”为假,因为“1 > 1”为假。这都是由于 JS 中比较运算符的从左到右关联性
if(Number(0) < Number(5) < Number(3)) {
alert("True");
}
或者试试这个:
if(Number(0) < Number(5) && Number(5) < Number(3)) {
alert("True");
}
我在谷歌上搜索了这个,因为我得到了
(3 >= 20) //returning true
,我猜javascript正在尝试将
3
检查为布尔值,因为我从
elm.getAttribute();
函数中获取了这个值,而
console.log();
以字符串形式打印。