2016-08-02 111 views
2

在javascript中将变量值转换为(返回)数组?

var a = [10,20,30,40]; 
 
var b = [11,22,33,44]; 
 
var c = [40,30,20,10]; 
 

 
var d = ["a","b","c"]; 
 

 
var e = d[2]; 
 

 
console.log(e[0]);

如何使变量e(即字符串“C”)的作为阵列的名称的javascript治疗字符串值,以便E [0]将在位置返回40而不是字符[0] 。感谢您的支持,并对不起,如果这是一个愚蠢的问题。

+0

OP - 你需要把三个数组到一个对象或使用胜利dow对象(不建议)。你要求的是[动态变量名称](http://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript)。 – evolutionxbox

回答

6

而不是字符串将数组的引用作为元素。

var d = [a, b, c]; 

var a = [10, 20, 30, 40]; 
 
var b = [11, 22, 33, 44]; 
 
var c = [40, 30, 20, 10]; 
 

 
var d = [a, b, c]; 
 

 
var e = d[2]; 
 

 
console.log(e[0]);


另一种方法是使用 eval()方法,但我不喜欢这种方法。

参见:Why is using the JavaScript eval function a bad idea?

3

您可能需要使用eval

var e = eval(d[2]); 

但是,您需要使用eval事实通常意味着你做别的东西不对。使用包含数组数组的单个变量,而不是每个包含数组的变量,最有可能会更好。 Pranav C Balan's answer是从单个数组中创建数组数组的一种方法。

+0

我不认为这会导致OP要求的结果。 OP希望e等于40。 – evolutionxbox

+0

@evolutionxbox他希望'e [0]'是40,因为他希望'e'是''引用'c'。 – Paulpro

+0

是的,你是对的 – evolutionxbox

2

你可以做到这一点,如果你的数组对象的键:

var arrays = { 
    a: [10, 20, 30, 40], 
    b: [11, 22, 33, 44], 
    c: [40, 30, 20, 10], 
} 

var d = ['a', 'b', 'c']; 

var e = d[2]; 

console.log(arrays[e][0]); // Will output "40". 

这避免了使用eval()这可能是不安全的!

OR如果你真的很需要那abc是一个变量,而不是一个对象键,你可以做@pranav答案:

var d = [a, b, c]; 

这将为你原来的数组的引用,那么你可以这样做:

console.log(d[2][0]); // Will output "40" too! 
0

请勿使用双引号。

var d = [a,b,c]

然后

console.log(e[0][0]) will return the element you want 
0

在你想要的方式,你可以用this关键字做

var a = [10,20,30,40]; 
 
var b = [11,22,33,44]; 
 
var c = [40,30,20,10]; 
 

 
var d = ["a","b","c"]; 
 

 
var e = this[d[2]]; 
 

 
console.log(e[0]);