簡體   English   中英

無法使用變量訪問對象屬性

[英]Cannot access object property using variable

我有一個看起來像這樣的對象:

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

現在有一個功能:

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

這是HTML:

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

它將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
}

它使用setName參數。

我的問題是-為什么第二個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

因為任何屬性的值都是字符串。 因此,在您的情況下, data-set-name返回字符串"set_1" ,而不是對變量set_1的引用。 如果您的set_1變量是全局變量,則應該可以執行以下操作-

console.log(window[setName].cards)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM