可以用jQuery做这个吗?
jQuery代码
var bla = [ "hello", "world", "!" ];
var foo = 'bla';
foo = new Array();
alert(foo[0]); // how to return 'hello'?
使用深层复制(或任何方法):
var bla = [ "hello", "world", "!" ];
var foo = 'bla';
myarray = $.extend(true, {}, foo);
alert(myarray[0]); // how to return 'hello'?
@edit:
这个例子:
http://jsfiddle.net/rafuzeles/r9fY8/7/
HTML
<div class="mydiv" id="bla">Go</div>
<div class="mydiv" id="mydiv_name_of_array">Go 2</div>
<div class="mydiv" id="mydiv_some_array">Go 3</div>
<div class="mydiv" id="mydiv_another_array">Go 4</div>
的jQuery
$('.mydiv').click(function () {
var bla = ["hello", "world", "!"];
var mydiv_name_of_array = ["hel", "wor", "ffs"];
var mydiv_some_array = ["Hi", "Cat", "Dog"];
var mydiv_another_array = ["Green", "Black", "Nice"];
var mydiv_name_of_array = ["Air", "Plane", "Good"];
var div_id = this.id;
var myarray = $.extend(true, {}, div_id); // div_id = name of array
alert(myarray[0]); // how to return value of array?
});
答案 0 :(得分:1)
如何:http://jsfiddle.net/r9fY8/10/
$('.mydiv').click(function () {
var id = $(this).attr('id'); // get id of clicked div
var object_of_arrays = { // use an object so we can get named items
bla : ["hello", "world", "!"],
mydiv_name_of_array : ["hel", "wor", "ffs"],
mydiv_some_array : ["Hi", "Cat", "Dog"],
mydiv_another_array : ["Green", "Black", "Nice"]
};
var myarray = object_of_arrays[id]; // get the array with the same name as our id
alert(myarray[0]); // returns hello, hel, Hi, or Green
});
我相信这可以解决你所要求的案件。如果您不介意,请务必将此答案标记为正确 - 尝试提高我的StackOverflow分数。 :)
答案 1 :(得分:0)
首先,您要通过javascript创建一个数组。
var bla = [ "hello", "world", "!" ];
您正在初始化变量并分配String值,如:
var foo = 'bla';
您正在将foo的值赋给空数组
foo = new Array();
然后
alert(myarray[0]);
它应该返回undefined。
这样做。
var bla = [ "hello", "world", "!" ];
var foo = bla;
alert(foo[0]);
答案 2 :(得分:0)
//#1使用foo ='bla'中的单个qoutes它不被视为变量而是一个字符串如果从中移除单个qoutes它将起作用
//#2这需要完全删除,因为它会清除foo中的所有内容,因此当它进入警报foo时它是空的
var bla = [ "hello", "world", "!" ];
var foo = 'bla'; //#1
foo = new Array(); //#2
alert(foo[0]); // how to return 'hello'?