繁体   English   中英

了解这个 Javascript 解决方案

[英]Understanding this Javascript solution

我正在尝试更新我的 Javascript。 我试图了解这个解决方案是如何完全工作的。 它把所有的 arrays 加起来,所以返回 [1, 4, 7],但我真的很想了解它的每一部分。 如果有人愿意提供帮助,我将不胜感激,谢谢。

var array = [
  [1],
  [2, 1, 1],
  [3, 4]
];

let m = array.map(function(item) {

  return item.reduce(function(acc, curr) {
    acc += curr;
    return acc;
  }, 0)
})

console.log(m)

数组中的每个子数组都通过Array.prototype.map() function 映射到其元素的总和。 Array.prototype.reduce()一种将数组缩减为单个值(在本例中为总和)的函数式方法。

var array = [
  [1],
  [2, 1, 1],
  [3, 4]
];
// map each sub-array in the array to a new value
let m = array.map(function(item) {

  // for each element in the sub-array, add it to the accumulator (acc)
  return item.reduce(function(acc, curr) { 
    acc += curr;
    return acc;
  }, 0) // initialize acc = 0
})

console.log(m)

Array.prototype.map() 参考

Array.prototype.reduce() 参考

暂无
暂无

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

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