| re: multidimensional associative array
chuck wrote:[color=blue]
> hi,
> I have a table of prices that is dependent on the size of item, and
> the number of that item.
> something like this(i am sure the formating won't come out correctly)[/color]
It didn't ;-)
[color=blue]
> ...........1".........1.25"
> 100.....$25.......$30
> 500.....$100.....$125
> 1000...$190.....$230
> 2500...$450.....$500
>
> i want to do something like
> priceArray['oneInch'][500] and get 100
>
> I set up this array
> var priceArray = [ {100:25, 500:100, 1000:190, 2500:450},
> {100:30, 500:125, 1000:230, 2500:500}];
>
> and can reference like this
>
> priceArray[0][500] and get 100
>
> but how can I setup a text key like
>
> priceArray['oneInch'][500][/color]
Use an object, which means you loose the special features of an array
but likely you weren't using them anyway (though length may have been
handy). Declare your price object using either (I've changed the name):
var priceObj = {};
priceObj['1.0'] = {100:25, 500:100, 1000:190, 2500:450};
priceObj['1.5'] = {100:30, 500:125, 1000:230, 2500:500};
or
var priceObj = {
'1.0' : {100:25, 500:100, 1000:190, 2500:450},
'1.5' : {100:30, 500:125, 1000:230, 2500:500}
};
whichever is best for you (remember not to put a comma after the last
member of priceObj in the second method). The index can be any string
you like, I've used decimal numbers for convenience. I suppose you
could use words or phrases but that doesn't seem sensible to me:
var priceObj = {
'one inch' : {100:25, 500:100, 1000:190, 2500:450},
'one point five inches' : {100:30, 500:125, 1000:230, 2500:500}
};
You can access the values by:
alert( priceObj['1.0'][500] );
Since you don't have a length, you can't use a typical for loop like
for(... i<priceObj.length; ...) to loop through priceObj, so use for..in:
var prices = [ 'size - qty : price'];
var qty, s, sizes;
for ( s in priceObj ) {
sizes = priceObj[s]
for ( qty in sizes ) {
prices.push( s + '" - ' + qty + ': $' + sizes[qty] );
}
}
alert( prices.join('\n'));
--
Rob |