简体   繁体   English

如何使用reduce在Javascript中返回一个object?

[英]How to use reduce to return an object in Javascript?

I'm trying to count the number of odd and even numbers in an array by using the Array.reduce() method.我正在尝试使用 Array.reduce() 方法计算数组中奇数和偶数的数量。 When I run the below code, I get the error "odd is not defined."当我运行下面的代码时,出现错误“未定义奇数”。 How/where do I define odd to get this code to work?我如何/在何处定义 odd 以使此代码起作用?

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

Well, odd isn't defined. 好吧,奇数没有定义。 What you should do is either put odd/even in quotes ( counts['odd'] ) or use dot notation ( counts.odd ). 您应该做的是在引号( counts['odd'] )中使用奇数/偶数,或者使用点符号( counts.odd )。

Also, since odd and even aren't defined, incrementing them would result into NaN . 另外,由于未定义奇数和偶数,因此递增它们将导致NaN The initial value should instead be { odd: 0, even: 0 } . 初始值应改为{ odd: 0, even: 0 }

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

This is a function that can do it for you. 此功能可以为您完成此任务。

 function oddEvenCounts(arr) { const counts = { even: 0, odd: 0 }; arr.forEach(n => { if(n % 2 === 0) { counts.even++; } else { counts.odd++ } }); return counts; } const array = [5, 3, 8, 6, 9, 1, 0, 2, 2]; console.log(oddEvenCounts(array)); 

Answer using ES6+使用 ES6+ 回答

const sumEvenOdd = (numbersArray) => {
    return numbersArray.reduce((acc, current) => current % 2 === 0 ? {...acc,'even':acc['even'] + current} : {...acc, 'odd':acc['odd'] + current}, {"even":0, "odd":0})
}'

console.log(sumEvenOdd([1, 6, 8, 5, 3]));
// Expected results: {even: 14, odd: 9}

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

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