JavaScript reduce()方法行为与数组数组

时间:2019-03-04 08:57:54

标签: javascript arrays

我有下一个数组数组:

[ 
  [ {inner: {text: ["name"]}}, {inner: {text: ["height"]}}, {inner: {text: ["country"]}} ],
  [
    [ {text: ["Kilimanjaro"]}, {text: ["5895"]}, {text: ["Tanzania"]} ],
    [ {text: ["Everest"]}, {text: ["8848"]}, {text: ["Nepal"]} ],
    [ {text: ["Mount Fuji"]}, {text: ["3776"]}, {text: ["Japan"]} ],
    [ {text: ["Mont Blanc"]}, {text: ["4808"]}, {text: ["Italy/France"]} ],
    [ {text: ["Vaalserberg"]}, {text: ["323"]}, {text: ["Netherlands"]} ],
    [ {text: ["Denali"]}, {text: ["6168"]}, {text: ["United States"]} ],
    [ {text: ["Popocatepetl"]}, {text: ["5465"]}, {text: ["Mexico"]} ],
  ]
]

“内部”和“文本”是2个构造函数的实例。到目前为止非常简单。

还有下一个函数可以使用该数组:

function rowHeights(rows) {
  return rows.map(function(row) {
    return row.reduce(function(max, cell) {
      return Math.max(max, cell.minHeight());
    }, 0);
  });
}

minHeight()仅返回数组的长度+ 1(如果从“内部”调用)。或者只是数组的长度(如果从“文本”中调用)。

让我向您展示我希望该功能如何工作:

rows[ 
  row[0][ {inner: {text: ["name"]}}, {inner: {text: ["height"]}}, {inner: {text: ["country"]}} ],
  row[1][
    reduce[0][ {text: ["Kilimanjaro"]}, {text: ["5895"]}, {text: ["Tanzania"]} ],
    reduce[1][ {text: ["Everest"]}, {text: ["8848"]}, {text: ["Nepal"]} ],
    reduce[2][ {text: ["Mount Fuji"]}, {text: ["3776"]}, {text: ["Japan"]} ],
    and so on...[ {text: ["Mont Blanc"]}, {text: ["4808"]}, {text: ["Italy/France"]} ],
    [ {text: ["Vaalserberg"]}, {text: ["323"]}, {text: ["Netherlands"]} ],
    [ {text: ["Denali"]}, {text: ["6168"]}, {text: ["United States"]} ],
    [ {text: ["Popocatepetl"]}, {text: ["5465"]}, {text: ["Mexico"]} ],
  ]
]

这就是它的实际工作方式:

rows[ 
  row[0][ {inner: {text: ["name"]}}, {inner: {text: ["height"]}}, {inner: {text: ["country"]}} ],
  row[1][
    [reduce[0] {text: ["Kilimanjaro"]},reduce[1] {text: ["5895"]},reduce[2] {text: ["Tanzania"]} ],
    [reduce[0] {text: ["Everest"]},reduce[1] {text: ["8848"]},reduce[2] {text: ["Nepal"]} ],
    [and so on... {text: ["Mount Fuji"]}, {text: ["3776"]}, {text: ["Japan"]} ],
    [ {text: ["Mont Blanc"]}, {text: ["4808"]}, {text: ["Italy/France"]} ],
    [ {text: ["Vaalserberg"]}, {text: ["323"]}, {text: ["Netherlands"]} ],
    [ {text: ["Denali"]}, {text: ["6168"]}, {text: ["United States"]} ],
    [ {text: ["Popocatepetl"]}, {text: ["5465"]}, {text: ["Mexico"]} ],
  ]
]

rowHeights的结果是:

[2, 1, 1, 1, 1, 1, 1, 1]

我理解第一个要素。它比较第一个数组的3个元素并返回2。

我的问题在它开始与第二个数组一起使用时出现。

我对reduce()rowHeights()的理解是什么?

P.S。这是Eloquent Javascript第2版书籍中的示例。如果您想查看完整的代码,请单击here

0 个答案:

没有答案