从函数中访问javascript对象

use*_*598 2 javascript object javascript-objects

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

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

Sha*_*313 5

在你的第二个代码中,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
Run Code Online (Sandbox Code Playgroud)