How to access a specific object in javascript?
I am a bit of a noob when it comes to this. I am using JSON to define a class/object called product
and I am not sure how to pass arguments to access a certain part of that object. Pardon me for not being able to explain it better. Hopefully my code sample will help:
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 (produc开发者_如何学编程tQty,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
}
};
This is how I am accessing it currently, works great.
var myProduct = product.getPrice(144,2);
As I said in the comment in the above code sample, I'd like to not hard code p20lb.one, 'p20lb' would be an argument I could pass to getPrice, and 'one' would also be an argument. So maybe something like this:
getPrice: function (productQty,colorQty,productName,tier) {
return this.productName.tier * productQty;
}
var myProduct = product.getPrice(144,2,'14lb','two');
But that is no go, I get undefined
no matter what I do. I'm clearly a noob when it comes to this. Is what I'm trying to do possible? If so, can you point me in the right direction? Thanks!
Try this[productName][tier]
instead. In JavaScript, the dot notation and bracket notation are identical. That is, obj.a
is the same as obj['a']
.
Simple.
getPrice: function (productQty,colorQty,productName,tier) {
return this[productName][tier] * productQty;
}
Objects can be accessed in array notation. Don't forget to wrap it in a try-catch block to handle the cases where a certain key combination does not exist.
Can you just do:
var colorQty = product.p20lb.one;
var myProduct = product.getPrice(144, colorQty);
getPrice: function (productQty, colorQty) {
return productQty * colorQty;
}
精彩评论