使用数组值作为数组名称

时间:2014-01-13 09:58:33

标签: javascript jquery

我试图将数组值作为arg传递给函数,然后使用它的值来引用另一个数组。我知道这听起来有点复杂,但我这样做有一个原因;)我认为showProject认为project1是一个字符串,因为它只返回'p'和...任何帮助赞赏?

var projects = ["project1","project2"];

var project1 = ["image1","image2"];
var project2 = ["image1","image2"];

function showProject(arr){

    console.log(arr[0]);

}

//why isn't this showing image 1 in project 1 array?
showProject(projects[0]);

小提琴> http://jsfiddle.net/4ryLT/

5 个答案:

答案 0 :(得分:4)

这似乎是你想要的:

jsFiddle

var project1 = ["image1","image2"];
var project2 = ["image1","image2"];

var projects = [project1,project2];

function showProject(arr){

    alert(arr[0]);

}

showProject(projects[0]);

将数组设置为projects数组的元素。

答案 1 :(得分:0)

var projects = ["project1","project2"];

var project1 = ["image1","image2"];
var project2 = ["image1","image2"];

function showProject(arr){

    console.log(eval(arr)[0]);

}

showProject(projects[0]);

答案 2 :(得分:0)

var projects指的是其他两个变量吗? 如果是,请删除""并按其他顺序排列

var project1 = ["image1","image2"];
var project2 = ["image1","image2"];
var projects = [project1,project2];

function showProject(arr){

alert(arr[0]);

}

showProject(projects[0]);

http://jsfiddle.net/4ryLT/3/

答案 3 :(得分:0)

我认为你的意思是

var projects = [];

projects["project1"] = ["image1","image2"];
projects["project2"] = ["image1","image2"];


function showProject(arr){

   alert(arr[0]);

}

showProject(projects["project1"]);

答案 4 :(得分:-1)

不改变你的逻辑:

var projects = ["project1","project2"];
var project1 = ["image1","image2"];
var project2 = ["image1","image2"];


function showProject(arr){

    console.log(eval(arr)[0]);

}
showProject(projects[0]);

byee