我可以使用链式比较运算符语法吗?
在一个 JS 库中,我看到了这样的语法:
if (val > 5 == t) { ... }
我在控制台中测试了这个:
1 == 1 == 2 // false
2 > 1 == 1 // true
1 == 2 == 1 // false
1 == 1 == 1 // true
1 < 2 < 3 // true
1 > 2 > 3 // false
乍一看一切正确。这个可以用吗?
In one JS library I saw such syntax:
if (val > 5 == t) { ... }
I tested this in console:
1 == 1 == 2 // false
2 > 1 == 1 // true
1 == 2 == 1 // false
1 == 1 == 1 // true
1 < 2 < 3 // true
1 > 2 > 3 // false
At first glance all correct. Can this be used?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
...等等。
如果您想了解转换,您应该搜索
==
运算符,该运算符使用 抽象相等比较算法。...and so on.
If you're wondering about the conversion, you should do a search on the
==
operator, which uses the Abstract Equality Comparison Algorithm.JavaScript 不支持数学中使用的链式比较语法:
相反,它从左到右评估每个比较,这有时会产生与数学链式比较相同的结果,就像所有示例一样,但过程不同:
出于这个原因,应该劝阻。
不过,要回答你的问题,是的,可以使用它。
Javascript does not support the chained comparison syntax used in mathematics:
Instead, it evaluates each comparison left to right, which can sometimes yield the same results as mathematical chained comparison, as do all your examples, but the process is different:
For this reason, it should be discouraged.
To answer your question, however, yes it can be used.
您并没有真正比较您认为正在比较的内容:
这就是为什么严格相等
===
在所有情况下都会失败You not really comparing what you think you are comparing:
Which is why strict equality
===
will fail in all cases这是一种正确的语法,但不是我推荐的语法。发生的情况可能是:
左侧的布尔值隐式转换为 int。
It's a correct syntax but not one I would recommend. What's happening, is probably:
With the boolean on the left implicitly converted to an int.
没有什么可以阻止您使用这种冒险的语法,但是请记住,JavaScript 代码中出现错误的最常见原因之一就是搞乱 运算符优先级。
因此,强烈建议通过向优先级组添加括号来显式定义优先级,以防它们包含多个优先级可明确确定的简单数学表达式。
There is nothing to stop you from using such an adventurous syntax however do keep in mind that one of the most frequent reasons for having bugs inside JavaScript code is messing up operator precedence.
Therefore its strongly advised to explicitly define precedence by adding brackets to precedence groups in case they consist of more than simple mathematical expressions for which the precedence is clearly determinable.
另一个问题是类型强制。
jslint
输出:Another concern is type coercion.
jslint
output: