()括号,它在JavaScript中的({__ proto:[]} instanceof Array)语句中做了什么 [英] () brackets, what does it do in the statement of ({__proto__: []} instanceof Array) in JavaScript
问题描述
在JavaScript中,以下内容给出错误:
In JavaScript, the following gives an error:
{ __proto__: [] } instanceof Array;
如果我将其包围在(括号)
它没有错误:
If I surround it in (brackets)
it has no error:
({ __proto__: [] } instanceof Array);
为什么会这样?
推荐答案
当解释器看到 {
,默认情况下,它会认为您正在声明一个新的块,例如
When the interpreter sees a {
, by default, it will think that you're declaring a new block, such as
{
console.log('foo');
}
结果:
{
__proto__: []
} instanceof Array
没有多大意义 - 你不能 instanceof
一个块。
doesn't make much sense - you can't instanceof
a block.
但当它被包裹时在括号中,解释器知道期望在括号内的值,而不是块 - 所以它将内部的所有内容评估为表达式,并且(正确地)解析 {__ proto _1:[]}
作为对象。
But when it's wrapped in parentheses, the interpreter knows to expect a value inside the parentheses, not a block - so it evaluates everything inside as an expression instead, and (properly) parses { __proto__: [] }
as an object.
这正是为什么,当解构为时已经完全相同的原因分配变量,你必须在括号周围加上括号:
This is exactly the same reason why, when destructuring to already assigned variables, you have to put parentheses around the line:
let x, y;
({x, y} = { x: 'foo', y: 'bar'});
console.log('done ' + x);
有效,但没有()
:
let x, y;
{x, y} = { x: 'foo', y: 'bar'};
console.log('done ' + x);
这篇关于()括号,它在JavaScript中的({__ proto:[]} instanceof Array)语句中做了什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!