2012-03-20 112 views
1

我希望能够通过使用字符串来引用数组,因为这样的:如何使用jQuery中的另一个变量通过名称引用变量?

var arrayName = "people"; 

var people = [ 
    'image47.jpeg', 
    'image48.jpeg', 
    'image49.jpeg', 
    'image50.jpeg', 
    'image52.jpeg', 
    'image53.jpeg', 
    'image54.jpeg', 
    'image55.jpeg', 
] 

function myFunc (arrayName) 
{ 
    //arrayName is actually just a string that evaluates to "people", which then in turn would reference the var people, which is passed in. 
} 

如何做到这一点有什么想法?对不起,如果我错过了明显的东西。

+0

'变种arrayName中的[] =人[]',这需要来_after_ var people []。 – Ohgodwhy 2012-03-20 02:09:01

+0

看到这个http://stackoverflow.com/questions/952457/javascript-using-variable-as-array-name – 2012-03-20 02:13:30

回答

2

您可以简单地创建一个全球性的词典,如:

var people = ['image47.jpeg', 'image48.jpeg']; 
var cars = ['image3.png', 'image42.gif']; 
var global_arrays = { 
    people: people, 
    cars: cars 
}; 

function myFunc(arrayName) { 
    var ar = global_arrays[arrayName]; 
    // Do something with ar 
} 

注意myFunc的第一行清楚地表明,这是一种具有myFunc的只是一种复杂的方式接受摆在首位数组本身。我强烈建议你做到这一点,就像这样:

function myFunc(ar) { 
    // Do something with ar 
} 
myFunc(people); 

这意味着你的代码会被其他人(比如,想要第三方插件渲染长颈鹿),并且不需要任何全局变量可重复使用。

1

如果你的阵列功能之外声明,则可以使用this关键字,像这样访问:

function myFunc(arrayname) { 
    var itemzero = this[arrayname][0]; 
} 
0
var arrayName = "people"; 

var people = [ 
    'image47.jpeg', 
    'image48.jpeg', 
    'image49.jpeg', 
    'image50.jpeg', 
    'image52.jpeg', 
    'image53.jpeg', 
    'image54.jpeg', 
    'image55.jpeg', 
] 

function myFunc (arrayName) 
{ 

//Here you can use this or window obj To quote you array. 
//such as window[arrayName] 

} 
相关问题