我想通过以下代码创建一个多维数组。
var i = 0;
$('.button_image').each(function () {
buttons[i]['left'] = $(this).position().left;
buttons[i]['top'] = $(this).position().top;
i++;
});
数组应该是这样的
buttons[1]['left']=10;
button[1][top]=20;
buttons[2]['left']=40;
button[2][top]=50;
但它在 firefox 控制台上给出了以下错误。
TypeError: buttons[i] is undefined
buttons[i]['left']=$(this).position().left;
请告诉我我的代码有什么问题。提前致谢。
我想要这种格式:
[rows] => Array (
[0] => Array (
[column1] => hello
[column2] => hola
[column3] => bonjour )
[1] => Array (
[column1] => goodbye
[column2] => hasta luego
[column3] => au revoir ) )
最佳答案
Javascript 没有多维数组,它只有数组的数组或对象的对象等。
因此,要在另一个数组中创建一个数组,您需要先将初始数组本身的元素 i
定义为一个数组。您只需在 each
循环中添加初始化 buttons[i] = [];
即可。
但是,您真正需要的是对象而不是数组,因为数组只能有数字索引,例如 buttons[0][2]
,而对象可以有任意索引,如 buttons[0]['left']
或等效符号 buttons[0].left
就像你在问题中写的那样。
// this is making buttons[i] a new object:
buttons[i] = {}; // the preferred notation over "new Object();"
// now this works without problem:
buttons[i]['left'] = $(this).position().left;
buttons[i]['top'] = $(this).position().top;
// equivalent notation:
buttons[i].left = $(this).position().left;
关于javascript - 如何创建javascript多维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20470013/