gpt4 book ai didi

没有大括号的 Javascript 键/值对

转载 作者:搜寻专家 更新时间:2023-10-31 23:37:34 24 4
gpt4 key购买 nike

我注意到在 nodejs 和浏览器中,你可以给出一个不带大括号的键/值对,它被接受了。它的计算结果为该对的值的一半。例如:

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

但是如果你引用id,那么 Node 需要更多的输入:

> "id": 5
...

那么这里发生了什么?没有大括号的 id: 5 是什么语法?

最佳答案

这不是错误。您正在声明一个标签,后跟一个 Number 文字。

控制台默认打印出代码中最后一个表达式的结果。

因此它打印5

您的困惑源于这样一个事实:完全相同的语法可能意味着完全不同的事物,这取决于上下文

这是由 JavaScript 解析器根据规范的规则来决定的。

另一个例子是:

{}

那是对象字面量还是 block ?上下文提供了答案。

来自 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.

关于没有大括号的 Javascript 键/值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38271692/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com