简体   繁体   English

冒号在这个JavaScript代码段中是什么意思(不是对象文字)?

[英]What does the colon mean in this JavaScript snippet (not an object literal)?

I apologize for posting a duplicate-looking question, (I know, that there is a bunch of similar titled questions here), but none of the questions already present seems to suit my case. 我为发布一个看似复制的问题而道歉,(我知道,这里有一堆类似的标题问题),但是现有的问题似乎都不适合我的情况。

In short, what does the colon do here: 简而言之,冒号在这里做了什么:

<script>
  'use strict';
  foo: 1;

  //whatever else
</script>

I supposed this to be a syntax error, but it's not. 我认为这是一个语法错误,但事实并非如此。 And it's not a label, I think, since adding a line break foo; 我认为,这不是一个标签,因为添加了一个换行符break foo; throws Uncaught SyntaxError: Undefined label 'foo' (though a doc page suggests exactly this, that it's a label). 抛出Uncaught SyntaxError: Undefined label 'foo' (尽管文档页面恰好表明了这一点,它是一个标签)。

I suppose this is some recent addition to the JavaScript syntax, since I have never heard of such use of the colon. 我想这是JavaScript语法的一些新增内容,因为我从未听说过冒号的这种用法。


If anyone wonders, why I'm asking this, this is my explanation: I was reading an MDN doc page and there is an example: 如果有人想知道,为什么我问这个,这是我的解释:我正在阅读MDN文档页面并且有一个例子:

var func = () => { foo: 1 };               
// Calling func() returns undefined!

It shows, that the curly braces in this case are treated as block delimiters and not an object literal. 它表明,在这种情况下,花括号被视为块分隔符而不是对象文字。 So I supposed, that somehow foo: 1 on its own must be syntactically legal. 所以我认为,不知何故foo: 1本身必须在语法上合法。 And indeed it is. 事实确实如此。

There is a question , which is supposed to cover every use of the colon in JavaScript, but it doesn't mention this, and no answer there does this either. 一个问题 ,应该涵盖JavaScript中每次使用冒号,但它没有提到这一点,也没有答案。

If you'd have read further down the page you linked, you would see why it was written like that. 如果你已经在你链接的页面上进一步阅读,你就会明白为什么它是这样写的。

var func = () => { foo: 1 };

This is an attempt to return an object from a arrow function. 这是尝试从箭头函数返回对象。

That doesn't work for reasons explained here: 由于这里解释的原因,这不起作用:

This is because the code inside braces ( {} ) is parsed as a sequence of statements (ie foo is treated like a label, not a key in an object literal). 这是因为大括号( {} )中的代码被解析为一系列语句(即foo被视为标签,而不是对象文字中的键)。 ( source ) 来源

So the returned value needs to be wrapped in parentheses: 所以返回的值需要包含在括号中:

var func = () => ({foo: 1});

To actually answer your question: 要真正回答你的问题:

It's a label. 这是一个标签。

You can't just take the foo: 1 out of context like that. 你不能只是采取foo: 1这样的上下文。

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

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