简体   繁体   中英

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?

{test: 10, 7}

How is this trailing 7 valid if it doesn't have a key?

Is this a special JS object literal syntax? Where can I read more about it and why it evaluated to 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 '}'

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?

When I do:

{test: 10, 7, 8}

I then get 8

I also get an error if I try JSON notation:

{'test': 10, 7}

Whats going on here?

The object isn't relevant; 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.

There are 2 things happening here, but the key thing is that this is not a JavaScript object literal. As you've seen, const test = {test: 10, 7} fails.

Firstly, {let foo=7;} is valid code; the braces are being used as block scope , not object notation.

Secondly, test: statement is being used to label a statement , not as a key in an object.

So your code is the same as:

{
    test:
    (10, 7)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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