2011-01-21 68 views
1

當談到這件事時,我有些不自在。我使用JSON來定義一個名爲product的類/對象,我不確定如何傳遞參數來訪問該對象的某個部分。請原諒我不能更好地解釋它。希望我的代碼示例將有所幫助:如何訪問JavaScript中的特定對象?

var product = { 
    p14lb: { 
     one: 10.00, 
     two: 20.00, 
     three: 30.00, 
     four: 40.00, 
     five: 50.00, 
     six: 60.00, 
     colorCharge: 2.00 
    }, 
    p20lb: { 
     one: 20.00, 
     two: 30.00, 
     three: 40.00, 
     four: 50.00, 
     five: 60.00, 
     six: 70.00, 
     colorCharge: 1.00 
    }, 
    getPrice: function (productQty,colorQty) { 

     // I can get the values like this   
     return this.p20lb.one * productQty; 

     // but i'd like to be able to pass in the value of what object I want to access 
     // so instead of hard coding p20lb.one, 'p20lb' would be an argument I could pass 
     // to getPrice, and 'one' would also be an argument 

    } 
}; 

這就是我目前如何訪問它,效果很好。

var myProduct = product.getPrice(144,2); 

正如我在上面的代碼示例中的評論稱,我想硬編碼p20lb.one,「p20lb」將是一個說法,我可以傳遞給用getPrice,和「一」也會是一個爭論。因此,也許是這樣的:

getPrice: function (productQty,colorQty,productName,tier) { 

    return this.productName.tier * productQty; 

} 

var myProduct = product.getPrice(144,2,'14lb','two'); 

但是,這是不走,我得到undefined不管我做什麼。當談到這一點時,我顯然是一個noob。我正在嘗試做什麼?如果是這樣,你能指出我正確的方向嗎?謝謝!

+2

BTW:你指什麼叫做 「對象字面值」,而不是JSON。 JSON是[非常嚴格的字符串格式](http://json.org/),可以通過JavaScript的`eval()`來理解。您的示例是有效的JavaScript,但絕對不符合JSON。 – Tomalak 2011-01-21 00:49:06

回答

4

改爲嘗試this[productName][tier]。在JavaScript中,點符號和括號表示法是相同的。即,obj.aobj['a']相同。

1

簡單。

getPrice: function (productQty,colorQty,productName,tier) { 

    return this[productName][tier] * productQty; 

} 

可以用數組表示法訪問對象。不要忘記將它包裝在try-catch塊中以處理某些組合鍵不存在的情況。

0

可你只是做:

var colorQty = product.p20lb.one; 
var myProduct = product.getPrice(144, colorQty); 

getPrice: function (productQty, colorQty) { 
    return productQty * colorQty; 
} 
相關問題