Javascript“元组”符号:它的意义是什么?
在 wtfjs,我发现以下是合法的javascript。
",,," == Array((null,'cool',false,NaN,4)); // true
参数 (null,'cool',false,NaN,4)
对我来说看起来像一个元组,但 javascript 没有元组!
我的 javascript 控制台中的一些快速测试产生以下结果。
var t = (null,'cool',false,NaN,4); // t = 4
(null,'cool',false,NaN,4) === 4; // true
(alert('hello'), 42); // shows the alert and returns 42
它的行为似乎与分号 ;
分隔的语句列表完全相同,只是返回最后一个语句的值。
是否有参考文献描述了这种语法及其语义?它为什么存在,即什么时候应该使用它?
At wtfjs, I found that the following is legal javascript.
",,," == Array((null,'cool',false,NaN,4)); // true
The argument (null,'cool',false,NaN,4)
looks like a tuple to me, but javascript does not have tuples!
Some quick tests in my javascript console yields the following.
var t = (null,'cool',false,NaN,4); // t = 4
(null,'cool',false,NaN,4) === 4; // true
(alert('hello'), 42); // shows the alert and returns 42
It appears to behave exactly like a semicolon ;
separated list of statements, simply returning the value of the last statement.
Is there a reference somewhere that describes this syntax and its semantics? Why does it exist, i.e. when should it be used?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您将看到逗号运算符的效果。
计算
a,b,c,...,n
时的结果值将始终是最右边表达式的值,但是链中的所有表达式仍然被计算(从左到右)。You are seeing the effect of the comma operator.
The resultant value when
a,b,c,...,n
is evaluated will always be the value of the rightmost expression, however all expressions in the chain are still evaluated (from left to right).正如已经解释的那样,此行为是由
,
运算符引起的。因此,表达式(null,'cool',false,NaN,4)
的计算结果始终为4
。所以我们有Array(4)
- 创建分配了 4 个元素的新数组。在与字符串进行比较时,该数组将转换为字符串,就像使用Array(4).toString()
一样。对于数组,toString
的作用类似于在此数组上调用的join(',')
方法。因此,对于 4 个元素的空数组,连接将生成字符串",,,"
。As already explained this behaviour is caused by
,
operator. Due to this the expression(null,'cool',false,NaN,4)
will always evaluate to4
. So we haveArray(4)
- creates new array with allocated 4 elements. At the time of comparison with the string this array is converted to string like it would be withArray(4).toString()
. For arraystoString
acts likejoin(',')
method called on this array. So for the empty array of 4 elements join will produce the string",,,"
.试试这个
alert((null,'cool',false,NaN,4))
然后你就可以看到了。demo
原因是因为逗号运算符会计算所有语句并返回最后一个语句。
想想这一行:
a = 1, b = 2, c = 3;
它将运行每个表达式,因此本质上它将把变量设置为你想要的并返回最后一个值(在本例中) 3)Try this
alert((null,'cool',false,NaN,4))
and then you can see.demo
The reason is because the comma operator evaluates all the statements and return the last one.
Think of this line:
a = 1, b = 2, c = 3;
it will run each expression so in essence it will set the variables to what you want and return the last value (in this case 3)