【发布时间】:2013-07-17 21:27:35
【问题描述】:
为什么第一个起作用而不是后者? *它只是一个微小的区别,在后一种情况下,我使用速记来访问猫对象属性。我读到如果“属性的名称是一个有效的变量名称——当它没有任何空格或符号并且不以数字字符开头时”,它不应该有任何区别。
//this works
var cats = {Spot:true};
function addCat (name) { cats[name] = true; }
addCat("white");
console.log ("white" in cats); //true
console.log (cats.white); //true
//this doesn't work
var cats = {Spot:true};
function addCat (name) { cats.name = true; }
addCat("white");
console.log ("white" in cats); //false
console.log (cats.white); //undefined
【问题讨论】:
-
cats.name不是动态的。 -
试试
console.log(cats),你会发现问题 -
cats.name在cats上设置一个名为'name'的属性。
标签: javascript object javascript-objects