javascript - 枚举中的点符号与括号符号

javascript - dot vs bracket notation in enumeration

我知道点符号和括号符号之间存在一些差异,但对于这个特定问题,我有点困惑为什么点符号不起作用而括号却起作用。

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!");
    }
}

我有点困惑的部分是 guns[speargun].heft 这会正常工作,但如果我这样做 guns.speargun.heft 那么它将是不确定的。

既然 rockSpearguns 中的属性都是一个词,难道 gun.speargun 还不能调出属性吗?

我想有点原因,因为现在 speargun 是一个字符串,如果将其放入 gun.speargun 它实际上会变成类似于 gun."speargun" 因为如果使用括号表示法我们只是做gun[speargun] 而不是使用 gun["speargun"] 因为这只会使它成为一个错误的双引号。

是啊真的很暧昧,有个经验法则:

  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);
    

顺便说一句,您可以在两种情况下使用括号,但我更喜欢选择我刚才提到的,因为使用括号看起来您是在处理数组而不是对象

希望对您有所帮助

相当于

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

guns['Sharpshooter'].heft

guns.Sharpshooter.heft

因为计算了方括号中的变量,将内容插入到括号中。你得到第二段。

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

在你上面的例子中,你使用

guns.speargun.heft

不存在,因为您在对象 guns.

中没有 属性 speargun

它不起作用,因为 rockSpearguns 对象中没有鱼枪 属性。

The reason is that in a JS object, all property keys are strings. When you use dot notation, JS is thinking you are looking for a key with the explicit key of whatever is after the dot.

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

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

我建议你阅读this article