javascript - dot vs bracket notation in enumeration

时间:2016-10-15 17:21:55

标签: javascript object properties notation

I do know there's some differences between dot and bracket notations but for this specific problem I am a bit confused why the dot notation wouldn't work and bracket does.

var rockSpearguns = {
  Sharpshooter: {barbs: 2, weight: 10, heft: "overhand"},
  Pokepistol: {barbs: 4, weight: 8, heft: "shoulder"},
  Javelinjet: {barbs: 4, weight: 12, heft: "waist"},
  Firefork: {barbs: 6, weight: 8, heft: "overhand"}
};

function listGuns (guns) {
    for(var speargun in guns){
        console.log("Behold! "+speargun+", with "+ guns[speargun].heft +" heft!");
    }
}

the part I am a bit confused is guns[speargun].heft this would work properly but if I do guns.speargun.heft then it will be undefined.

Since the properties in the rockSpearguns are all just one word shouldn't gun.speargun still able to call out the properties too?

I have thought a bit was the reason because now speargun is a string that if putting into gun.speargun it actually becomes something like gun."speargun" because if using bracket notation we just do gun[speargun] instead of using gun["speargun"] because this will just make it a double quote which is wrong.

3 个答案:

答案 0 :(得分:1)

是的,确实含糊不清,有一条经验法则:

  1. 在动态生成要访问的属性值时使用括号,例如:

    var Person = {
        name: 'John',
        lastName: 'Doe'
    };
    
    var propertyToCheck = 'name';
    
    console.log(Person.propertyToCheck); //error!
    console.log(Person[propertyToCheck]); //correct way
    
  2. 在未动态生成要访问的属性值时使用点(事先知道该属性),例如:

     var Person = {
         name: 'John',
         lastName: 'Doe'
     };
    
    console.log(Person.name);
    
  3. 顺便说一下,你可以在两种情况下都使用括号,但我更喜欢选择上面提到的内容,因为使用括号似乎是在使用数组而不是对象

    希望这有助于你

答案 1 :(得分:1)

相当于

speargun = 'Sharpshooter';
guns[speargun].heft

guns['Sharpshooter'].heft

guns.Sharpshooter.heft

因为评估方括号中的变量并将内容插入括号中。你得到第二段。

如果您有一个字符串文字,那么您可以将它用作带有点的对象的property accessor

在上述情况下,您使用

guns.speargun.heft

不存在,因为对象speargun中没有属性guns

答案 2 :(得分:1)

它无效,因为rockSpearguns对象中没有speargun属性。

  

原因是在JS对象中,所有属性键都是字符串。当你使用点符号时,JS认为你正在寻找一个带有点后面的显式键的键。

在您的代码中,var speargun被rockSpearguns对象中每个属性的字符串值替换。

因此,guns[speargun].heft会转换为guns["Sharpshooter"].heft

我建议你阅读this article