JS 三元运算符混淆
我现在正在学习三元运算符。我已经掌握了基础知识,但后来我看到了这个片段,它对我来说没有任何意义。谁能解释一下它是如何组合在一起的?
b.m & 4 || (c |= 2, 63 <= a && 77 >= a ? a = 65 : 48 <= a && 57 >= a ? a = 48 : c & 1 ? 97 <= a && 122 >= a ? a = 65 : 197 == a || 229 == a ? c &= 5 : 192 <= a && 687 >= a ? a = 192 : 1536 <= a ? a = 1536 : 912 <= a ? a = 912 : 160 <= a ? a = 160 : 127 <= a ? c &= 5 : 33 <= a ? a = 59 : c &= 5 : 48 > a ? c &= 5 : 65 > a ? a = 59 : 96 > a ? c &= 5 : 112 > a ? a = 96 : 187 > a ? c &= 5 : a = 59);
bm& 4 || 据我理解是位运算,然后 (c |= 2, 另一个位运算,但是逗号是什么意思?!
然后是 [第 63 回] 77 >= 一个? a = 65 : 48
转换为
if(a >= 63 && a <= 77){ 一个= 65 } 别的 { a = 48; }
然后是 <= a && 57 >= 一个? a = 48:c & 1 ? 97 <= a 这对我来说根本没有任何意义。因为 48 是针对前一个语句的。任何人都可以
I'm learning about ternary operators now. I got the basics down, but then I saw this snippet and it doesn't make any sense to me. Can anyone please explain how is it put together?!
b.m & 4 || (c |= 2, 63 <= a && 77 >= a ? a = 65 : 48 <= a && 57 >= a ? a = 48 : c & 1 ? 97 <= a && 122 >= a ? a = 65 : 197 == a || 229 == a ? c &= 5 : 192 <= a && 687 >= a ? a = 192 : 1536 <= a ? a = 1536 : 912 <= a ? a = 912 : 160 <= a ? a = 160 : 127 <= a ? c &= 5 : 33 <= a ? a = 59 : c &= 5 : 48 > a ? c &= 5 : 65 > a ? a = 59 : 96 > a ? c &= 5 : 112 > a ? a = 96 : 187 > a ? c &= 5 : a = 59);
b.m & 4 || are bit operations as far as I understood, then (c |= 2, another bit operation, but what does comma mean?!
Then there's
63 <= a && 77 >= a ? a = 65 : 48
which translates to
if(a >= 63 && a <= 77){
a = 65
} else {
a = 48;
}
and then after that comes <= a && 57 >= a ? a = 48 : c & 1 ? 97 <= a which doesn't make any sense to me at all. because 48 was for the previous statement. Can anyone
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
逗号是 JavaScript 中的一个单独的运算符:
你只掌握了表达的一部分:
实际上它有点长(有一些格式):
尝试用 if-else 方式重写它会产生以下结果:
请注意 if-else 方法缺乏返回当前值,而三元运算符确实返回最后执行的运算符的值(这可能会影响括号中布尔表达式的整体值)。
Comma is a separate operator in javascript:
You have grasped just a part of expression:
Actually it is a little bit longer (with some formatting):
Trying to rewrite it in if-else fasion will yield the following result:
Please, pay attention that if-else approach lacks returning value currently, whereas ternary operator does return the value of the last operator executed (this may affect the overall value of boolean expression in parentheses).
我更喜欢格式化嵌套三元语句像这样,所以它们有一个简单、可读的结构:
遵循该结构,它看起来像这样:
I prefer to format nested ternary statements like this, so they have a simple, readable structure:
Following that structure, it would look something like this:
逗号不是三元运算符,它允许两个表达式替换一个表达式。
但更重要的是,这是一团糟。将其分解、格式化并评论。除非你正在打高尔夫球,否则将所有这些合并成一堆简直就是虐待。
The comma isn't a ternary operator, it allows two expressions to replace one.
But more importantly, that's a mess. Break it down, format it, and comment it. Unless you're golfing, combining all of that into one pile is just abusive.