简体   繁体   English

为什么 object 文字上的尾随值会返回该值?

[英]Why does having a trailing value on an object literal return that value?

I can do:我可以:

{test: 10}

But how is this valid JS and why do I get 7 when I add this to the chrome js console?但是这个有效的 JS 是怎样的,为什么当我将它添加到 chrome js 控制台时会得到 7?

{test: 10, 7}

How is this trailing 7 valid if it doesn't have a key?如果它没有密钥,这个尾随 7 如何有效?

Is this a special JS object literal syntax?这是特殊的 JS object 文字语法吗? Where can I read more about it and why it evaluated to 7?我在哪里可以阅读更多关于它的信息以及为什么它评估为 7?

When I do: const test = {test: 10, 7}; // VM140:1 Uncaught SyntaxError: Unexpected token '}'当我这样做时: const test = {test: 10, 7}; // VM140:1 Uncaught SyntaxError: Unexpected token '}' const test = {test: 10, 7}; // VM140:1 Uncaught SyntaxError: Unexpected token '}'

That gives me a expected error so how come without assigning it to a variable it is valid JS and the console returns to me the value 7?这给了我一个预期的错误,那么为什么不将它分配给一个变量它是有效的 JS 并且控制台返回给我值 7?

When I do:当我做:

{test: 10, 7, 8}

I then get 8然后我得到 8

I also get an error if I try JSON notation:如果我尝试 JSON 表示法,我也会收到错误消息:

{'test': 10, 7}

Whats going on here?这里发生了什么?

The object isn't relevant; object 不相关; the not very useful comma operator returns the last value.不是很有用的逗号运算符返回最后一个值。

console.log( (10, 7) ) // 7

We need extra parentheses here so that it's not interpreted as a second argument to 'console.log`, but the same thing is happening.我们在这里需要额外的括号,这样它就不会被解释为“console.log”的第二个参数,但同样的事情正在发生。

There are 2 things happening here, but the key thing is that this is not a JavaScript object literal.这里发生了两件事,但关键是这不是 JavaScript object 文字。 As you've seen, const test = {test: 10, 7} fails.如您所见, const test = {test: 10, 7}失败。

Firstly, {let foo=7;} is valid code;首先, {let foo=7;}是有效代码; the braces are being used as block scope , not object notation.大括号被用作块 scope ,而不是 object 表示法。

Secondly, test: statement is being used to label a statement , not as a key in an object.其次, test: statement被用于label 语句,而不是 object 中的键。

So your code is the same as:所以你的代码是一样的:

{
    test:
    (10, 7)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM