【发布时间】:2013-04-23 08:51:31
【问题描述】:
我发现用括号括起不同的语句会返回最后一个:
(34892,47691876297,2000) => 2000
('test',73,document.createElement('p')) => <p></p>
而且我还发现不管怎样,所有的语句都被执行了:
(console.log('test'), console.log('test2'), console.log('test3'), 6)
将记录:
test
test2
test3
结果将是 6。
不过,我也发现有些语句不能用:
(throw new Error(), 10) => SyntaxError: Unexpected token throw
(if (1) console.log('test'), 5) => SyntaxError: Unexpected token if
那么,这个括号-逗号符号的意义何在?您可以轻松地执行所有语句,然后使用最后一条语句的值。这个是来做什么的?我是不是用错了?
【问题讨论】:
-
许多语言都以这种方式工作; Scala 就是这样工作的。
-
@RobertHarvey 那么,这样做有什么意义呢?我不明白为什么你不能只执行所有的语句。
-
throw似乎很明显。第二个例子表明该列表只接受基本表达式,而不接受复杂的代码结构。 -
34892和console.log('test')是表达式,if和throw是语句。您可以将运算符(包括逗号运算符)应用于表达式,但不能应用于语句。
标签: javascript comma parentheses