Javascript如何正确访问关联数组元素

时间:2013-11-29 17:28:45

标签: javascript associative-array

我在理解如何从二维关联数组中访问元素时遇到了一些困难。例如,当我尝试使用第一个数组中的“price”键时,它将返回为对象Object。我很难返回与键相关的值。我也试过没有引用。谢谢你的时间。

var houseData = Array(
    {
        "price": "$320, 000",
        "imgsrc": "./images/colonial.jpg",
        "description": "Colonial House, 3 bedrooms"
    },
    {
        "price": "$459, 999",
        "imgsrc": "./images/contemporary.jpg",
        "description": "Colonial House, 3 bedrooms"
    },
    {
        "price": "$179, 500",
        "imgsrc": "./images/cottage.jpg",
        "description": "Colonial House, 3 bedrooms"
    },
    {
        "price": "$210, 000",
        "imgsrc": "./images/ranch.jpg",
        "description": "Colonial House, 3 bedrooms"
    },
    {
        "price": "$159, 999",
        "imgsrc": "./images/townhouse.jpg",
        "description": "Colonial House, 3 bedrooms"
    });

1 个答案:

答案 0 :(得分:2)

基本上,JS中的括号将创建一个对象。使用Array函数,您将创建一个对象列表。因此,正如@Salehen Rahman所说,您需要首先通过指定索引来访问列表中的对象:

var objectAtIndex0 = houseData[0];

然后访问对象中的数据:

var priceFromObjectAtIndex0 = objectAtIndex0.price;

或单行:

var priceFromObjectAtIndex0 = houseData[0].price;