简体   繁体   中英

Javascript, jquery - Call array position by using a variable name

I have 2 arrays:

var array1 = [50,60];
var array2 = [120,180];

I am passing a value to a variable like this:

var curId = $(this).attr('id');

I want to set the content of #result to a computation like this:

$(#result).text(number * curId[0]);

Number is a variable predefined by me, and curId[0] shoul actually translate to array1[0] or array2[0], depending on the css class.

Can anyone tell me the right syntax for this? I'm pretty noob at js. Thanks.

You can use a variable to hold the array that you want to use:

var myArray;

if (something)
    myArray = array1;
else
    myArray = array2;

$('#result').text(number * myArray[0]);

If you're trying to get the array in a variable from a string containing the name of the variable, you should use an object, like this:

var arrays = {
    array1: [50,60],
    array2: [120,180]
};

var myArray = arrays[curId];

$('#result').text(number * myArray[0]);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM