为什么结果是8?
Why the result is 8?
今天我参加了关于 JS 的工作面试,其中一个问题是
a的值是多少
var a = (3,5 - 1) * 2;
嗯,我假设它是 8(chrome 开发控制台也给它 8)但我不知道为什么它是 8。为什么 3
被省略了?我的意思是你当然不能用它做任何操作,但它仍然消失了,或者我错了?
请放轻松。我正在努力理解。任何关于此类操作的文章将不胜感激
The comma operator evaluates each of its operands (from left to right) and returns the value of the last (right-most) operand.
所以,var a = (3,5 - 1) * 2;
returns 4 * 2 = 8
查看此参考资料:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator
逗号运算符计算列出的所有表达式,returns 最后一个。所以你的表达简化为
(5 - 1) * 2
3,5
它不是 3.5
(浮动)。参见 comma operator
The comma operator evaluates each of its operands (from left to right)
and returns the value of the last operand.
3,5 等于 5。
(3,5 - 1) * 2
转换为 (5 - 1) * 2
即 8.
今天我参加了关于 JS 的工作面试,其中一个问题是
a的值是多少
var a = (3,5 - 1) * 2;
嗯,我假设它是 8(chrome 开发控制台也给它 8)但我不知道为什么它是 8。为什么 3
被省略了?我的意思是你当然不能用它做任何操作,但它仍然消失了,或者我错了?
请放轻松。我正在努力理解。任何关于此类操作的文章将不胜感激
The comma operator evaluates each of its operands (from left to right) and returns the value of the last (right-most) operand.
所以,var a = (3,5 - 1) * 2;
returns 4 * 2 = 8
查看此参考资料:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator
逗号运算符计算列出的所有表达式,returns 最后一个。所以你的表达简化为
(5 - 1) * 2
3,5
它不是 3.5
(浮动)。参见 comma operator
The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.
3,5 等于 5。
(3,5 - 1) * 2
转换为 (5 - 1) * 2
即 8.