英文:
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[''])
<!-- 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
是一个数字字面量,当后面跟着 ['objectPropertyName']
时,它会被解释为一个 Number 对象。它没有一个叫 ''
的属性,因此当你调用 1['']
时返回 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 ['objectPropertyName']
. It does not have a property ''
, and thus returns undefined
when you call 1['']
.
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论