多维数组JAVASCRIPT出错了

时间:2016-04-21 19:05:08

标签: javascript arrays multidimensional-array

嘿伙计们,我需要帮助,请:P

此代码有什么问题?

var arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
var narr = []; // want to be like that [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

function arange(mass) {
    for (var i = 0; i < mass.length; i++) {
        for (var j = 0; j < mass[i].length; j++) {
            narr[mass[i]].push(mass[j][i]);
        }
    }
}

如果我调用该函数有一个问题:&#34; TypeError:无法读取属性&#39; push&#39;未定义的。&#34;谢谢。 另外link here

4 个答案:

答案 0 :(得分:1)

您不小心尝试在值push上调用narr而不是数组本身。当然,原始值没有定义push函数。您的代码应如下所示:

var mass = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
var narr = [];

function arange(mass) {
    for (var i = 0; i < mass.length; i++) {
        var innerArray = [];
        for (var j = 0; j < mass[i].length; j++) {
            innerArray.push(mass[j][i]);
        }
        narr.push(innerArray);
    }
}

答案 1 :(得分:1)

只需选择正确的元素来分配值。

var arr = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ];

function arange(mass) {
    var narr = [];
    for (var i = 0; i < mass.length; i++) {
        for (var j = 0; j < mass[i].length; j++) {
            narr[j] = narr[j] || [];
            narr[j][i] = mass[i][j];
        }
    }
    return narr;
}

document.write('<pre>' + JSON.stringify(arange(arr), 0, 4) + '</pre>');

ES6

var arr = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ];

function arange(mass) {
    var narr = [];
    mass.forEach((a, i) => a.forEach((b, j) => {
        narr[j] = narr[j] || [];
        narr[j][i] = mass[i][j];
    }));
    return narr;
}

document.write('<pre>' + JSON.stringify(arange(arr), 0, 4) + '</pre>');

答案 2 :(得分:0)

您需要添加一个临时数组来存储中间值:

var arr = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ];

var narr = []; 

function arange(mass) {
    for (var i = 0; i < mass.length; i++) {
        var t = []; // temporary array
        for (var j = 0; j < mass[i].length; j++) {
            t.push(mass[j][i]);
        }
        narr.push(t);
    }
}

arange(arr);

document.write(JSON.stringify(narr));

答案 3 :(得分:0)

或者你可以使用这个ES6一个班轮

&#13;
&#13;
var arr = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ];
    
var res = arr.map((e, i) => e.map((_, j) => arr[j][i]));

document.write(JSON.stringify(res));
&#13;
&#13;
&#13;