Javascript Reduce方法创建累加器对象

时间:2017-09-20 20:38:53

标签: javascript reduce

var numbers = [5, 3, 8, 6, 9, 1, 0, 2, 2];
var oddEvenCounts = numbers.reduce(function(counts, number) {
  if (isOdd(number)) {
    counts[odd]++;
  } else {
    counts[even]++;
  }
}, {});

我正在寻找这段代码中的错误(仍在学习reduce方法;)) - 我哪里出错?

2 个答案:

答案 0 :(得分:7)

带注释的工作代码:

var numbers = [5, 3, 8, 6, 9, 1, 0, 2, 2];

function isOdd(n) {
  return !!(n % 2);
}

var oddEvenCounts = numbers.reduce(function(counts, number) {
  if (isOdd(number)) {
    counts.odd++; // use dot notation or ['odd']
  } else {
    counts.even++;  // use dot notation or ['even']
  }
  
  return counts; // return the accumulator
}, { odd: 0, even: 0 }); // set the initial values of odd and even

console.log(oddEvenCounts);

您可以使用括号表示法和三元运算符来缩短代码:

var numbers = [5, 3, 8, 6, 9, 1, 0, 2, 2];

function isOdd(n) {
  return !!(n % 2);
}

var oddEvenCounts = numbers.reduce(function(counts, number) {  
  counts[isOdd(number) ? 'odd' : 'even']++;
  
  return counts;
}, { odd: 0, even: 0 });

console.log(oddEvenCounts);

答案 1 :(得分:1)

返回你的累加器:

var numbers = [5, 3, 8, 6, 9, 1, 0, 2, 2];
var oddEvenCounts = numbers.reduce(function(counts, number) {
  if (isOdd(number)) {
    counts[odd]++;
  } else {
    counts[even]++;
  }
  return counts;
}, {});