我一直在网上阅读,一些地方说这是不可能的,一些地方说这是可能的,然后给出一个例子,另一些地方反驳这个例子,等等。
如何在JavaScript中声明一个2维数组?(假设这是可能的) 我如何访问它的成员?(myArray[0][1] or myArray[0,1]?)
我一直在网上阅读,一些地方说这是不可能的,一些地方说这是可能的,然后给出一个例子,另一些地方反驳这个例子,等等。
如何在JavaScript中声明一个2维数组?(假设这是可能的) 我如何访问它的成员?(myArray[0][1] or myArray[0,1]?)
当前回答
很少有人会使用“推”: 为了带来一些新的东西,我将向您展示如何用一些值初始化矩阵,例如:0或空字符串“”。 提醒一下,如果你有一个10个元素的数组,在javascript的最后一个索引将是9!
function matrix( rows, cols, defaultValue){
var arr = [];
// Creates all lines:
for(var i=0; i < rows; i++){
// Creates an empty line
arr.push([]);
// Adds cols to the empty line:
arr[i].push( new Array(cols));
for(var j=0; j < cols; j++){
// Initializes:
arr[i][j] = defaultValue;
}
}
return arr;
}
使用例子:
x = matrix( 2 , 3,''); // 2 lines, 3 cols filled with empty string
y = matrix( 10, 5, 0);// 10 lines, 5 cols filled with 0
其他回答
Javascript只有一维数组,但正如其他人指出的那样,你可以构建数组的数组。
下面的函数可以用来构造一个固定维度的二维数组:
function Create2DArray(rows) {
var arr = [];
for (var i=0;i<rows;i++) {
arr[i] = [];
}
return arr;
}
列的数量其实并不重要,因为在使用数组之前不需要指定数组的大小。
然后你可以调用:
var arr = Create2DArray(100);
arr[50][2] = 5;
arr[70][5] = 7454;
// ...
我修改了Matthew Crumley关于创建多维数组函数的回答。我已经添加了要作为数组变量传递的数组的维度,还有另一个变量- value,它将用于设置多维数组中最后一个数组的元素的值。
/*
* Function to create an n-dimensional array
*
* @param array dimensions
* @param any type value
*
* @return array array
*/
function createArray(dimensions, value) {
// Create new array
var array = new Array(dimensions[0] || 0);
var i = dimensions[0];
// If dimensions array's length is bigger than 1
// we start creating arrays in the array elements with recursions
// to achieve multidimensional array
if (dimensions.length > 1) {
// Remove the first value from the array
var args = Array.prototype.slice.call(dimensions, 1);
// For each index in the created array create a new array with recursion
while(i--) {
array[dimensions[0]-1 - i] = createArray(args, value);
}
// If there is only one element left in the dimensions array
// assign value to each of the new array's elements if value is set as param
} else {
if (typeof value !== 'undefined') {
while(i--) {
array[dimensions[0]-1 - i] = value;
}
}
}
return array;
}
createArray([]); // [] or new Array()
createArray([2], 'empty'); // ['empty', 'empty']
createArray([3, 2], 0); // [[0, 0],
// [0, 0],
// [0, 0]]
很少有人会使用“推”: 为了带来一些新的东西,我将向您展示如何用一些值初始化矩阵,例如:0或空字符串“”。 提醒一下,如果你有一个10个元素的数组,在javascript的最后一个索引将是9!
function matrix( rows, cols, defaultValue){
var arr = [];
// Creates all lines:
for(var i=0; i < rows; i++){
// Creates an empty line
arr.push([]);
// Adds cols to the empty line:
arr[i].push( new Array(cols));
for(var j=0; j < cols; j++){
// Initializes:
arr[i][j] = defaultValue;
}
}
return arr;
}
使用例子:
x = matrix( 2 , 3,''); // 2 lines, 3 cols filled with empty string
y = matrix( 10, 5, 0);// 10 lines, 5 cols filled with 0
使用全局对象Array并用数组填充项:
let arr = new Array(5).fill([]);
或者如果已知长度的2d数组:
let arr = new Array(5).fill(new Array(2));
这将构造任何维度的数组。
function makeArrayChildren(parent, firstDimension, ...dimensions) {
for (let i = 0; i < parent.length; i++) {
parent[i] = new Array(firstDimension);
if (dimensions.length != 0) {
makeArrayChildren(parent[i], ...dimensions);
}
}
}
function makeArray(firstDimension, ...dimensions) {
if (firstDimension == undefined) {
throw Exception("Too few dimensions");
}
let topArray = new Array(firstDimension);
if (dimensions.length != 0) makeArrayChildren(topArray, ...dimensions);
return topArray;
}
这里还有另外两个我想做的函数,我可以用它作为一个完整性检查:一个用于在多维数组中所有最低级别项上执行的每个函数,一个填充方法。
Array.prototype.dimensionalFill = function (value) {
for (let i = 0; i < this.length; i++) {
const elem = this[i];
if (elem instanceof Array) {
elem.dimensionalFill(value);
} else {
this[i] = value;
}
}
};
/*Unlike forEach, this also loops over undefined values. */
Array.prototype.dimensionalForEach = function (callableFunc, thisArg) {
if (thisArg != undefined) {
return this.dimensionalForEach(callableFunc.bind(thisArg));
}
for (let i = 0; i < this.length; i++) {
const elem = this[i];
if (elem instanceof Array) {
elem.dimensionalForEach(callableFunc);
} else {
callableFunc(elem, i, this);
}
}
};
这里有一个漂亮的小检查,它使用了所有的特性。所以至少,它不可能完全错误。
let arr = makeArray(10, 10, 5, 4);
arr.dimensionalFill(2);
let sum = 0;
arr.dimensionalForEach((elem) => {
sum += elem;
});
console.log(`sum: ${sum} === ${10 * 10 * 5 * 4 * 2}`);
值得一提的是,在这一点上,创建一个全新的结构将是一个更好的实践,但这很有趣。