简体   繁体   English

Javascript,jquery-使用变量名调用数组位置

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

I have 2 arrays: 我有2个数组:

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的内容设置为这样的计算:

$(#result).text(number * curId[0]); $(#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. Number是由我预定义的变量,并且curId [0]实际上应转换为array1 [0]或array2 [0],具体取决于css类。

Can anyone tell me the right syntax for this? 谁能告诉我正确的语法吗? I'm pretty noob at js. 我对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"? 那么curId将是字符串“ array1”还是“ 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. 这样做是创建一个对象( lookups )以包含您要查找的信息。 That object has the properties array1 and array1 , which are your arrays. 该对象具有属性array1array1 ,它们是您的数组。 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. 您从元素的ID中将字符串“ array1”或“ array2”放入变量curId ,然后您可以使用Javascript通过[]语法按属性名称查找属性的事实。 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. 从技术上讲,如果数组是在全局范围内声明的,则可以不使用lookups对象而做到这一点,但是,如果您对Javascript还是比较陌生的,我将不介绍原因,并且无论如何,我建议您使用一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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