So curId
will be the string "array1" or "array2"? Then you'd do it like this:
var lookups = {
array1: [50, 60],
array2: [120,180]
};
var curId = $(this).attr('id');
$('#result').text(number * lookups[curId[0]]);
What that does is create an object (lookups
) to contain this information you're looking up. That object has the properties array1
and array1
, which are your arrays. You get the string "array1" or "array2" from the ID of your element into the variable curId
, and then you use the fact that Javascript lets you look up properties by their name using []
syntax. All of these are the same:
a = lookups.array1;
// is the same as
a = lookups["array1"];
// is the same as
a = lookups["array" + "1"];
// is the same as
s = "array1";
a = lookups[s];
Technically, if your arrays are declared at global scope, you could do that without using the lookups
object, but if you're fairly new to Javascript I won't go into why, and regardless, I'd recommend using one.