将JavaScript语句括在括号中有什么意义? [英] What is the point of wrapping JavaScript statements in parentheses?
问题描述
我发现用括号括起来的不同语句将返回最后一个:
I have discovered that wrapping different statements in parentheses will return the last one:
(34892,47691876297,2000) => 2000
('test',73,document.createElement('p')) => <p></p>
而且我还发现所有语句仍然被执行:
And I also found out that all the statements are executed anyway:
(console.log('test'), console.log('test2'), console.log('test3'), 6)
Will log:
test
test2
test3
结果为6。
但是,我也发现某些语句无法使用:
However, I've also found that some statements can't be used:
(throw new Error(), 10) => SyntaxError: Unexpected token throw
(if (1) console.log('test'), 5) => SyntaxError: Unexpected token if
,则出现意外的标记那么,此括号逗号表示法的意义是什么?您可以轻松执行所有语句,然后使用最后一条语句的值。这个是来做什么的?我使用不正确吗?
So, what is the point of this parenthesis-comma notation? You could easily execute all the statements and then use the last statement's value. What is this for? Am I using it incorrectly?
推荐答案
这是逗号运算符:)
它使您可以从左到右评估表达式,并返回最后一个操作数的结果(在您的情况下,该结果没有存储在任何地方,并且完全有效)。
It lets you evaluate expressions from left to right, returning the last operand's result (which, in your case, isn't stored anywhere, and is perfectly valid).
参考:
- http://www.ecma-international.org/ecma-262/5.1/#sec-11.14
- https://developer.mozilla.org/zh-CN/docs/JavaScript/参考/操作员/ Comma_Operator
- http://www.ecma-international.org/ecma-262/5.1/#sec-11.14
- https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Comma_Operator
这篇关于将JavaScript语句括在括号中有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!