Reduce return undefined?

I have an object called a student with two properties, a name and an account. I am trying to perform calculations using the score property, but I have problems accessing the resource from an array of students. I am currently trying to get the sum of points with the following code:

var sum = students.reduce(function(a, b) { 
                    return {sum: a.score + b.score}
                    })

This returns undefined and causes a weird display in firefox. I can't seem to find a mistake. There is no way to just simply access the parameters, i.e. Var myVar = myArray.myObject.myProperty;

+4
source share
3 answers

, , reduce. . - ""; , ( , ). - . , , :

var sum = students.reduce(function(a, s) {
    a.sum += s.score;
    return a;
}, { sum: 0 });

reduce ( , ). sum, .

, , ( sum), :

var sum = students.reduce(function(a, s) {
    return a += s.score;
}, 0);
+8

Ethan reduce, map .

students.map( student => student.score ).reduce( (a, b) => a + b, 0 );
+2

, . return. , a b. , , console.log, . , - reduce, . {sum: students[0].score + students[1].score}. . return; a b. , a - , , {sum: }, , score. , 192, {sum: {sum: 192}.score + students[2].score}. {sum: undefined + students[2].score}, , , NaN, - undefined NaN. .

, , a - {sum: 192}, , , , , . reduce , , , , , , sum. a . , reduce 0 .

, . , SO , , , , . . , , , . . https://developers.google.com/web/tools/chrome-devtools/. , ; http://ericlippert.com/2014/03/05/how-to-debug-small-programs/.

+2
source

All Articles