简体   繁体   中英

Javascript key/value pair with no braces

I noticed that in both nodejs and a browser, you can give a key/value pair with no braces, and it is accepted. It evaluates to the value half of the pair. For instance:

> { id: 5 }
{ id: 5 }
> id: 5
5

But if you quote id , then node wants more input:

> "id": 5
... 

So what is going on here? What syntax is id: 5 when it has no braces?

This is not a bug. You are declaring a label, followed by a Number literal.

The console defaults to printing out the result of the last expression in your code.

Hence it prints 5 .

Your confusion stems from the fact that the exact same syntax can mean totally different things, depending on the context .

This is for the JavaScript parser to decide according to the rules of the spec.

Another example would be:

{}

Is that an object literal or a block? The context provides the answer.

From the spec :

A Statement may be prefixed by a label. Labelled statements are only used in conjunction with labelled break and continue statements. ECMAScript has no goto statement. A Statement can be part of a LabelledStatement, which itself can be part of a LabelledStatement, and so on. The labels introduced this way are collectively referred to as the “current label set” when describing the semantics of individual statements.

Imagine you've written a nested for..loop .

for(var x = 0; x < 10; x++) {
  for(var y = 0; y < 10; y++) {
    if(thereIsAProblem) {
      break;
    }
  }
  console.log('done a column');
}

You want to break out of the inner loop and start the next iteration of the outer loop, but you don't want the console.log to run.

You can augment the loop with a label to specify exactly where you want to continue from.

outer: for(var x = 0; x < 10; x++) {
  for(var y = 0; y < 10; y++) {
    if(thereIsAProblem) {
      continue outer;
    }
  }
  console.log('done a column');
}

Although technically this is a standard feature in JavaScript, you won't see it used in the wild very often, because there's almost always a more idiomatic way to do things.

I think it's a bug of the JavaScript parser. When you type id : anything : 5 it outputs the same result (this works on Chrome too).

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