我想知道为什么这段代码错误Cannot read property 'odd' of undefined
:
var numbers = [5, 3, 8, 6, 9, 1, 0, 2, 2];
let isOdd = function(number){
return number % 2 !== 0;
}
var oddEvenCounts = numbers.reduce(function(counts, number) {
let odd;
let even;
if (isOdd(number)) {
counts[odd] = counts['odd'] + 1;
} else {
counts[even] = counts['even'] + 1;
}
}, {});
console.log(oddEvenCoutns(numbers));
// expected result
// counts = {
// odd: 1,
// even: 3
// }
你看到错误在哪里吗?它基本上指向计数[奇数]和计数[偶数]
答案 0 :(得分:2)
如果您想计算列表numbers
中的赔率和赔率数,那么我要么误解您的意图,要么您的预期输出错误。
// expected result
// counts = {
// odd: 1,
// even: 3
// }
当你的数组中有9个数字时没有意义。但是,我认为这个问题最适合作为mapreduce问题。因为您正在将相同的函数isOdd
应用(映射)到数组中的每个元素,然后将其减少为单个对象。
let numbers = [5, 3, 8, 6, 9, 1, 0, 2, 2];
// good job, this looks fine! +1 strict equality operator
const isOdd = function(number) {
return number % 2 !== 0;
}
// function to keep track of your odd and evens
const sumEvenOdd = function(acc, cur) {
if (true == cur) {
acc['odd'] += 1;
} else {
acc['even'] += 1;
}
return acc; // make sure you return your resulting object so it doesn't lose scope!
}
let foo = numbers.map( el => isOdd(el) ) // determine even or odd
.reduce( sumEvenOdd, {'even': 0,'odd': 0}); // sum even and odd!
console.log(foo); // {'even': 5, 'odd': 4}
答案 1 :(得分:0)
试试这个,你需要返回计数
var numbers = [5, 3, 8, 6, 9, 1, 0, 2, 2];
function isOddNumber(number){
return number % 2 !== 0;
}
var oddEvenCounts = numbers.reduce(function(counts, number) {
let odd;
let even;
if(isOddNumber()){
console.log(number)
counts['odd'] = number + 1;
} else {
counts['even'] = number + 1;
}
return counts;
}, {});
console.log(oddEvenCounts); // this is not a function it holds the value from reduce
答案 2 :(得分:0)
逐步mapreduce
let numbers = [5, 3, 8, 6, 9, 1, 0, 2, 2];
function is_odd(number) { return number % 2 !== 0; }
function get_counts(numbers) {
numbers = numbers.map(is_odd); // map is_odd over xs -> [true, true, false, false, true, true, false, false, false]
let odd_sum = numbers.reduce(function(sum, n) { return sum + n; }, 0); // reduce sum of true values -> 4
return { 'odd': odd_sum, 'even': numbers.length - odd_sum }
}
console.log(get_counts(numbers));
答案 3 :(得分:0)
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;
}, {odd: 0, even: 0});
function isOdd(number) {
return number % 2 === 1;
}
console.log(oddEvenCounts); // { "odd": 4, "even": 5 }