我一直在网上阅读,一些地方说这是不可能的,一些地方说这是可能的,然后给出一个例子,另一些地方反驳这个例子,等等。

如何在JavaScript中声明一个2维数组?(假设这是可能的) 我如何访问它的成员?(myArray[0][1] or myArray[0,1]?)


当前回答

下面的例子定义了一个名为activities的二维数组:

    let activities = [
        ['Work', 9],
        ['Eat', 1],
        ['Commute', 2],
        ['Play Game', 1],
        ['Sleep', 7]
    ];

在活动数组中,第一个维度表示活动,第二个维度显示每个活动每天花费的小时数。

要在控制台中显示活动数组,可以使用console.table()方法,如下所示:

console.table(activities);

输出如下所示:

┌─────────┬─────────────┬───┐ │(index)│0│1│ ├─────────┼─────────────┼───┤ │0│’Work’│9│ │1│’Eat’│1│ │2│’Commute’│2│ │3│’Play Game’│1│ │4│’Sleep’│7│ └─────────┴─────────────┴───┘

注意,(index)列用于表示内部数组的索引。

要访问多维数组的元素,首先使用方括号访问返回内部数组的外部数组的元素;然后使用另一个方括号访问内部数组的元素。

下面的例子返回上面activity数组中第一个内部数组的第二个元素:

console.log(activities[0][1]); // 9

向JavaScript多维数组中添加元素

您可以使用数组方法,如push()和splice()来操作多维数组的元素。

例如,要在多维数组的末尾添加一个新元素,可以使用push()方法,如下所示:

activities.push(['Study',2]);

┌─────────┬─────────────┬───┐ │(index)│0│1│ ├─────────┼─────────────┼───┤ │0│’Work’│9│ │1│’Eat’│1│ │2│’Commute’│2│ │3│’Play Game’│1│ │4│’Sleep’│7│ │5│’Study’│2│ └─────────┴─────────────┴───┘

要在数组中间插入一个元素,可以使用splice()方法。下面的代码将一个元素插入到activities数组的第二个位置:

activities.splice(1, 0, ['Programming', 2]);

┌─────────┬───────────────┬───┐ │(index)│0│1│ ├─────────┼───────────────┼───┤ │0│’Work’│9│ │1│’Programming’│2│ │2│’Eat’│1│ │3│’Commute’│2│ │4│’Play Game’│1│ │5│’Sleep’│7│ │6│’Study’│2│ └─────────┴───────────────┴───┘

这个示例计算在每个活动上花费的时间的百分比,并将该百分比附加到内部数组。

activities.forEach(activity => {
    let percentage = ((activity[1] / 24) * 100).toFixed();
    activity[2] = percentage + '%';
});

┌─────────┬───────────────┬───┬───────┐ │(index)│0│1│2│ ├─────────┼───────────────┼───┼───────┤ │0│’Work’│9│’38%’│ │1│’Programming’│2│’8%’│ │2│’Eat’│1│’4%’│ │3│’Commute’│2│’8%’│ │4│’Play Game’│1│’4%’│ │5│’Sleep’│7│’29%’│ │6│’Study’│2│’8%’│ └─────────┴───────────────┴───┴───────┘

从JavaScript多维数组中删除元素

要从数组中删除一个元素,可以使用pop()或splice()方法。

例如,下面的语句删除了activities数组的最后一个元素:

activities.pop();

┌─────────┬───────────────┬───┬───────┐ │(index)│0│1│2│ ├─────────┼───────────────┼───┼───────┤ │0│’Work’│9│’38%’│ │1│’Programming’│2│’8%’│ │2│’Eat’│1│’4%’│ │3│’Commute’│2│’8%’│ │4│’Play Game’│1│’4%’│ │5│’Sleep’│7│’29%’│ └─────────┴───────────────┴───┴───────┘

类似地,可以使用pop()方法从多维数组的内部数组中删除元素。下面的示例从活动数组的内部数组中删除百分比元素。

activities.forEach((activity) => {
    activity.pop(2);
});

┌─────────┬───────────────┬───┐ │(index)│0│1│ ├─────────┼───────────────┼───┤ │0│’Work’│9│ │1│’Programming’│2│ │2│’Eat’│1│ │3│’Commute’│2│ │4│’Play Game’│1│ │5│’Sleep’│7│ └─────────┴───────────────┴───┘

遍历JavaScript多维数组的元素

要迭代多维数组,可以使用嵌套for循环,如下例所示。

// loop the outer array

for (let i = 0; i < activities.length; i++) {
    // get the size of the inner array
    var innerArrayLength = activities[i].length;
    // loop the inner array
    for (let j = 0; j < innerArrayLength; j++) {
        console.log('[' + i + ',' + j + '] = ' + activities[i][j]);
    }
}

第一个循环遍历外部数组的元素,嵌套循环遍历内部数组的元素。

脚本在控制台中输出如下:

[0,0] =功 [0,1] = 9 [1,0] =吃 [1,1] = 1 [2,0] =通勤 [2,1] = 2 [3,0] =玩游戏 [3,1] = 1 [4,0] =睡眠 [4,1] = 7 [5,0] =学习 [5,1] = 2

或者你可以使用forEach()方法两次:

activities.forEach((activity) => {
    activity.forEach((data) => {
        console.log(data);
    });
});

工作 9 吃 1 上下班 2 玩游戏 1 睡眠 7 研究 2

其他回答

对于一行程序爱好者来说

// creates 8x8 array filed with "0"    
const arr2d = Array.from({ length: 8 }, () => Array.from({ length: 8 }, () => "0"))

另一个(来自dmitry_romanov的评论)使用Array().fill()

// creates 8x8 array filed with "0"    
const arr2d = Array(8).fill(0).map(() => Array(8).fill("0"))

使用ES6+扩展操作符(“受InspiredJW启发”:))

// same as above just a little shorter
const arr2d = [...Array(8)].map(() => Array(8).fill("0"))

还有另一种解决方案,它不强迫你预先定义2d数组的大小,而且非常简洁。

Var表= {} table[[1,2]] = 3 //注意双[[and]] Console.log (table[[1,2]]) // -> 3 .单击“确定”

这是因为,[1,2]被转换为一个字符串,用作表对象的字符串键。

使用数组推导式

在JavaScript 1.7及更高版本中,您可以使用数组推导式来创建二维数组。您还可以在填充数组时过滤和/或操作条目,而不必使用循环。

var rows = [1, 2, 3];
var cols = ["a", "b", "c", "d"];

var grid = [ for (r of rows) [ for (c of cols) r+c ] ];

/* 
         grid = [
            ["1a","1b","1c","1d"],
            ["2a","2b","2c","2d"],
            ["3a","3b","3c","3d"]
         ]
*/

您可以创建任何n x m的数组,并通过调用填充默认值

var default = 0;  // your 2d array will be filled with this value
var n_dim = 2;
var m_dim = 7; 

var arr = [ for (n of Array(n_dim)) [ for (m of Array(m_dim) default ]] 
/* 
         arr = [
            [0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0],
         ]
*/

更多示例和文档可以在这里找到。

请注意,这还不是一个标准功能。

我必须使一个灵活的数组函数添加“记录”到它,因为我需要,并能够更新它们,做任何计算e需要在我把它发送到数据库进行进一步处理。下面是代码,希望能有所帮助:)。

function Add2List(clmn1, clmn2, clmn3) {
    aColumns.push(clmn1,clmn2,clmn3); // Creates array with "record"
    aLine.splice(aPos, 0,aColumns);  // Inserts new "record" at position aPos in main array
    aColumns = [];    // Resets temporary array
    aPos++ // Increments position not to overlap previous "records"
}

请随意优化和/或指出任何错误:)

在一些注释中提到了这一点,但是使用array .fill()将有助于构造一个2-d数组:

function create2dArr(x,y) {
    var arr = [];
    for(var i = 0; i < y; i++) {
        arr.push(Array(x).fill(0));
    }
    return arr; 
}

这将在返回的数组中生成一个长度为x, y的数组。