簡體   English   中英

在javascript中使用變量值訪問JSON對象

[英]Using value of variable in javascript to access JSON Object

我正在嘗試使用HTML中某些文本的值訪問我的Pie對象。

但是,代碼使用的是變量的名稱,而不是變量的值。

對我來說,這似乎應該很明顯,但這讓我感到困惑。

謝謝

var pie = {

    welfare: {
        title: "Welfare",
        percentage : 24,
        point: 0,
        color: '#601C6B'
    },

    health: {
        title: "Health",
        percentage : 20,
        point: 0,
        color: '#FFAA97'
    },

    state_pensions: {
        title: "State pensions",
        percentage : 13,
        point: 0,
        color: "#9C9C9C"
    }
}


$('.pie_item').click(function(){

var pie_piece = $(this).text();

console.log("this is " + pie_piece);

$(this).closest(".drop_down_button").find('p').text(pie_piece);

console.log(pie.pie_piece);

});

當使用點符號對對象pie.pie_piece進行屬性訪問時, pie_piecepie對象中查找實際名稱為pie_piece的屬性。

要使用pie_piece的值,您將需要使用方括號表示法

pie[pie_piece]

有關財產訪問的更多信息

您可以使用object['element']表示法訪問object['element'] 因此,在這種情況下,如果pie_piece是welfarehealthstate_pensions ,則可以執行類似pie[pie_piece] state_pensions

    var pie = {

    welfare: {
        title: "Welfare",
        percentage : 24,
        point: 0,
        color: '#601C6B'
    },

    health: {
        title: "Health",
        percentage : 20,
        point: 0,
        color: '#FFAA97'
    },

    state_pensions: {
        title: "State pensions",
        percentage : 13,
        point: 0,
        color: "#9C9C9C"
    }
}


$('.pie_item').click(function(){

var pie_piece = $(this).text();

console.log("this is " + pie_piece);

$(this).closest(".drop_down_button").find('p').text(pie_piece);

console.log(pie[pie_piece]);

});

暫無
暫無

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

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