简体   繁体   English

无法使用变量访问对象属性

[英]Cannot access object property using variable

I have an object that looks like this: 我有一个看起来像这样的对象:

var set_1 = {
    id: 'set_1',
    nameofSet : 'English fruits',
    category: 'languages',
    cards : [
        {
            front : 'apple',
            back : 'jablko'
        },
        {
            front : 'orange',
            back : 'pomarancza'
        },
        {
            front : 'pear',
            back : 'gruszka'
        }
    ]
}

Now there's a function: 现在有一个功能:

$('#chooseSet').on('click', '.setName', function() {
    var setName = this.getAttribute("data-set-name");
    editCards(setName);
});

This is the HTML: 这是HTML:

<div class="setName" data-set-name="set_1">English fruits</div>

It gives the setName parameter to the editCards function that looks like this: 它将setName参数提供给editCards函数,如下所示:

editCards(setName) {
    console.log(setName); // logs "set_1"
    console.log(setName.cards); // logs "undefined" - why?
    console.log(set_1.cards);  // logs the `cards` array from `set_1'.
    // code
}

It takes the setName parameter. 它使用setName参数。

My question is - why doesn't the second console.log give me the cards' array as it does in the third console.log` example? 我的问题是-为什么第二个console.log cards' array as it does in the third console.log例子cards' array as it does in the third给我cards' array as it does in the third

Because any attribute's value is a string. 因为任何属性的值都是字符串。 So in your case data-set-name returns the string "set_1" , which is not a reference to the variable set_1 . 因此,在您的情况下, data-set-name返回字符串"set_1" ,而不是对变量set_1的引用。 If your set_1 variable is global, you should be able to do this instead - 如果您的set_1变量是全局变量,则应该可以执行以下操作-

console.log(window[setName].cards)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM