现场演示
function create2Array(d1, d2, fn) {
var arr = [],
d = function(x, y) {},
f = fn || d;
for (var i = 0; i < d1; i++) {
for (var j = 0, curr = []; j < d2; j++) {
curr[j] = f.call(window, i, j);
};
arr[i] = curr;
};
return arr;
};
function createArrayOfObjects(d1) {
var arr = [];
for (var i = 0; i < d1; i++) {
arr[i] = {};
};
return arr;
};
function print2DArray(arr) {
document.body.innerHTML += "<p><b>Array:</b></p>";
for (var i = 0, len = arr.length; i< len; i++) {
document.body.innerHTML += "<p><b>" + i + "</b>: " + arr[i].join(" ") + "</p>";
};
};
function printArrayOfObj(arr) {
document.body.innerHTML += "<p><b>Array:</b></p>";
for (var i = 0, len = arr.length; i< len; i++) {
document.body.innerHTML += "<p><b>" + i + "</b>: " + JSON.stringify(arr[i]) + "</p>";
};
};
var Server = {};
Server.Rows = createArrayOfObjects(10);
Server.Rows[0]["something"] = "test";
printArrayOfObj(Server.Rows);
像这样使用它:
Server.rows = create2Array(10, 10);
或者您甚至可以指定一个将索引作为参数的自定义初始化函数。假设你想用 0 默认初始化你的矩阵:
Server.rows = create2Array(10, 10, function(x, y) { return 0;});
或者如果你使用一个对象。
Server.rows = create2Array(10, 10);
Server.rows[0]["ServerUrl"] = "test";