1[''] 评估为undefined,但1[] 抛出 `Uncaught SyntaxError: Unexpected token ']`。

huangapple go评论59阅读模式
英文:

Why 1[''] evaluates to undefined, but 1[] throws `Uncaught SyntaxError: Unexpected token ']`

问题

JavaScript如何解释表达式1['']undefined,但1[]会抛出Uncaught SyntaxError: Unexpected token ']

    console.log(1['']) // 输出undefined

    console.log(1[]) // 抛出Uncaught SyntaxError: Unexpected token ']
英文:

How is Javascript interpreting the expression 1[''] as undefined, yet 1[] throws Uncaught SyntaxError: Unexpected token ']?

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

console.log(1[&#39;&#39;])

<!-- end snippet -->

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

console.log(1[])

<!-- end snippet -->

答案1

得分: 3

The subscript operator ([]) is used to access an object's properties.

1 是一个数字字面量,当后面跟着 [&#39;objectPropertyName&#39;] 时,它会被解释为一个 Number 对象。它没有一个叫 &#39;&#39; 的属性,因此当你调用 1[&#39;&#39;] 时返回 undefined

另一方面,1[] 只是一个语法错误 - 你不能省略你试图访问的属性。换句话说,你必须在大括号中有 某些东西

英文:

The subscript operator ([]) is used to access an object's properties.

1 is a number literal, which is evaluated as a Number object when followed by [&#39;objectPropertyName&#39;]. It does not have a property &#39;&#39;, and thus returns undefined when you call 1[&#39;&#39;].

1[], on the other hand, is just a syntax error - you can't omit the property you're trying to access. In other words, you have to have something in the braces.

huangapple
  • 本文由 发表于 2023年5月20日 20:47:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76295301.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定