简体   繁体   English

如何在JavaScript中添加多维数组值?

[英]How to add multidimensional array values in javascript?

I am pretty new to javascript.I am confused with javascript reduce. 我对javascript很陌生,对javascript reduce感到困惑。 this is my array value 这是我的数组值

var result = [ 
            [ 0, 4, 22 ]//26,
            [ 0, 9, 19 ]//28 
           ]

I want to add this array value like this.. 我想这样添加此数组值。

 [
     [26],
     [28]
    ]

And again I have to add this value like this.. 同样,我必须像这样添加此值。

26+28=54

this is my try this gives me undefined.. 这是我的尝试,这使我不确定。

var sum = result.map((data) => {
    data.reduce(function (total ,curr) {
        return total+curr
    })
});
console.log(sum)

You need a return statement in block statements 您需要在块语句中使用return语句

var sum = result.map(data => {
    return data.reduce(function (total, curr) {
//  ^^^^^^
        return total + curr;
    });
});

or without block statement 有无语句

var sum = result.map(data => data.reduce((total, curr) => total + curr));

To answer the last part question, I suggest to create a function for adding values and use it as callback for Array#reduce . 为了回答最后一部分的问题,我建议创建一个用于添加值的函数,并将其用作Array#reduce回调。

 var add = (a, b) => a + b, result = [[0, 4, 22], [0, 9, 19]], sum = result.map(a => a.reduce(add)), total = sum.reduce(add); console.log(sum); console.log(total); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM