【问题标题】:accessing javascript object from function [duplicate]从函数访问javascript对象[重复]
【发布时间】: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

【问题讨论】:

标签: javascript object javascript-objects


【解决方案1】:

在您的第二个代码中,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

【讨论】:

    猜你喜欢
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 1970-01-01
    • 2012-12-27
    • 2014-11-26
    相关资源
    最近更新 更多