How can I create a two dimensional array in JavaScript?
I have been reading online and some places say it isn't possible, some say it is and then give an example and others refute the example, etc.
How do I declare a 2 dimensional array in JavaScript? (assuming it's possible)
How would I access its members? ( myArray[0][1]
or myArray[0,1]
?)
var items = [
[1, 2],
[3, 4],
[5, 6]
];
console.log(items[0][0]); // 1
console.log(items);
您只需将数组中的每个项目都设置为一个数组。
var x = new Array(10);
for (var i = 0; i < 10; i++) {
x[i] = new Array(20);
}
x[5][12] = 3.0;
与activa的答案类似,下面是一个创建n维数组的函数:
function createArray(length) {
var arr = new Array(length || 0),
i = length;
if (arguments.length > 1) {
var args = Array.prototype.slice.call(arguments, 1);
while(i--) arr[length-1 - i] = createArray.apply(this, args);
}
return arr;
}
createArray(); // [] or new Array()
createArray(2); // new Array(2)
createArray(3, 2); // [new Array(2),
// new Array(2),
// new Array(2)]
链接地址: http://www.djcxy.com/p/19266.html