为什么第一个有效,而后者无效? *这只是一个微小的区别,在后一种情况下,我使用简写来访问 cats 对象属性。我读到,如果“属性名称是一个有效的变量名称——当它里面没有任何空格或符号并且不以数字字符开头时,它应该没有任何区别。”
//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
不是动态的,因此您无法在函数中获取 name
的值;但是,您正在设置一个名为 name
的属性:
//this works
var cats = {
Spot: true
};
function addCat (name) {
cats.name = true;
// use cats[name] like in your first example
}
addCat("white");
console.log(cats);
/*
{
Spot: true,
name: true
}
*/
console.log ("name" in cats); //true
console.log (cats.name); // true
关于javascript - 从函数访问 javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17731774/