为什么先工作而不是后者?*它只有一个小的区别,在后一种情况下,我使用速记来访问猫对象属性.我读到如果"属性的名称将是一个有效的变量名称 - 当它没有任何空格或符号并且不以数字字符开头时"它应该没有任何区别.
//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
Run Code Online (Sandbox Code Playgroud)
//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
Run Code Online (Sandbox Code Playgroud)