Javascript “tuple” notation: what is its point?

梦想与她 提交于 2019-11-28 21:04: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?


回答1:


You are seeing the effect of the comma operator.

The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.

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).




回答2:


As already explained this behaviour is caused by , operator. Due to this the expression (null,'cool',false,NaN,4) will always evaluate to 4. So we have

",,," == Array(4)

Array(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 with Array(4).toString(). For arrays toString acts like join(',') method called on this array. So for the empty array of 4 elements join will produce the string ",,,".




回答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)



来源:https://stackoverflow.com/questions/9018295/javascript-tuple-notation-what-is-its-point

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!