【问题标题】:Understanding a reduce function with if and bracket notation使用 if 和括号符号理解 reduce 函数
【发布时间】:2019-08-11 20:56:18
【问题描述】:

请解释代码并详细说明代码背后的运行情况。

我对 if 部分 if(! acc[key]) 感到困惑。是不是表示如果key不在acc中,用value数组设置key,跳出if语句,将obj压入acc键值?

如果 key 在 acc 中,则跳过 if 语句并使用另一个内存 acc[key] 并设置 acc 中的 key 并使用 obj 设置值。

我的解释正确吗?

var people = [{
    name: 'Alice',
    age: 21
  },
  {
    name: 'Max',
    age: 20
  },
  {
    name: 'Jane',
    age: 20
  }
];

function groupBy(objectArray, property) {
  return objectArray.reduce(function(acc, obj) {
    var key = obj[property];
    if (!acc[key]) {
      acc[key] = [];

    }
   acc[key].push(obj)
    return acc;

  }, {});
}
var groupedPeople = groupBy(people, 'age')
console.log(JSON.stringify(groupedPeople))

【问题讨论】:

  • 这里的代码不太行;无论它是否是第一个成员,您都应该推入分组对象(将 acc[key].push(obj) 移出条件块)。
  • 感谢我从我的练习代码中复制了它,所以我忘了更改代码。

标签: javascript square-bracket array-reduce


【解决方案1】:

if (!acc[key]) {...} 只是检查您是否已经在累加器中为该键捕获了任何数据。如果那里还没有任何内容,您可以在其中放置一个带有acc[key] = []; 的空数组,这样您就可以在下一步中将数据推送到它上面。

你的代码中的错误是你还在那个 if 子句中包含了push;这意味着您只会获得给定键的每个值的第一个对象。相反,您需要 all 该键的每个值的对象。

这是一个修复,代码中的一些 cmets 解释了它在每个步骤中所做的事情:

var people = [{
    name: 'Alice',
    age: 21
  },
  {
    name: 'Max',
    age: 20
  },
  {
    name: 'Jane',
    age: 20
  }
];

function groupBy(objectArray, property) {
  return objectArray.reduce(function(acc, obj) {
    // stepping through each object in the array:
    var key = obj[property]; // "key" is the value of the given property
                             // for this object
    if (!acc[key]) {         // if the accumulator doesn't already have
                             // data for that key,
      acc[key] = [];         // put an empty array there, so we can add
                             // data to it
    }
    // this next line was moved out of the if clause above it, because
    // you always want it to happen:
    acc[key].push(obj)       // push this object onto the accumulator 
                             // at that key
    return acc;              
  }, {});
}
var groupedPeople = groupBy(people, 'age')
console.log(JSON.stringify(groupedPeople))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    相关资源
    最近更新 更多