简体   繁体   English

使用[]表示法访问javaScript对象

[英]Accessing javaScript object using [ ] notation

What is difference between below: 下面有什么区别:

var ourDog = {
    "name": "Camper"
};

and

var ourDog = {
    name: "Camper",
};

And how it is able to return Camper for ourDog["name"] in both cases. 以及在两种情况下如何为我们的ourDog["name"]返回Camper

Is there any conversion happening behind the scene, when we access object properties with [] notation? 当我们使用[]表示法访问对象属性时,幕后是否发生任何转换?

Check the specs 检查规格

PropertyDefinition : PropertyName : AssignmentExpression PropertyDefinition:PropertyName:AssignmentExpression

  1. Return PropName of PropertyName. 返回PropertyName的PropName。

This part of spec suggests the formal syntax of the property name with its value. 规范的这一部分建议了属性名称及其值的形式语法。

Also, before that this part of the spec suggest that propertyName could be literalPropertyName which need not be described as a string . 此外,在之前, 规范的这一部分建议propertyName可以是literalPropertyName ,而无需描述为string

PropertyName[Yield] : PropertyName [Yield]:

LiteralPropertyName LiteralPropertyName

ComputedPropertyName[?Yield] ComputedPropertyName [?Yield]

LiteralPropertyName : LiteralPropertyName:

IdentifierName 标识符名称

StringLiteral 字符串字面量

NumericLiteral 数字文学

This is why you will get same result for both name and "name" . 这就是为什么name"name"都得到相同结果的原因。

However, if the property name is first name , then you need to use the string otherwise you will get a compilation error since after the property name a colon : is expected. 但是,如果属性名称是first name ,那么您需要使用字符串,否则会出现编译错误,因为在属性名称后应加上冒号:

//correct syntax
var ourDog = {
    "first name": "Camper"
};

//incorrect syntax
var ourDog = {
    first name: "Camper" //since after first there is no colon so there will be  compilation error
};

http://ecma-international.org/ecma-262/6.0/#sec-object-initializer http://ecma-international.org/ecma-262/6.0/#sec-object-initializer

A property name can only be an identifier name (ie identifiers + reserved words), a string literal, or a numeric literal. 属性名称只能是标识符名称(即标识符+保留字),字符串文字或数字文字。

you cant use a numeric literal with dot notation but bracket notation works: 您不能使用带点符号的数字文字,但是括号符号有效:

var ourDog = {
    123: "Camper",
};

Output 输出量

ourDog[123] // Camper

but

ourDog.123 // SyntaxError

for more information take a look into this 有关更多信息,请查看

Property names must be strings. 属性名称必须是字符串。 This means that non-string objects cannot be used as keys in the object. 这意味着非字符串对象不能用作对象中的键。 Any non-string object, including a number, is typecasted into a string via the toString method 通过toString方法将任何非字符串对象(包括数字)类型转换为字符串

var object = {};
object['1'] = 'value';
console.log(object[1]);

This outputs "value", since 1 is type-casted into '1'. 由于将1类型转换为“ 1”,因此将输出“值”。

Example is from MDN 示例来自MDN

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

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