减少返回未定义? [英] Reduce returning undefined?

查看:55
本文介绍了减少返回未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Student的对象,具有两个属性,名称和分数.我正在尝试使用score属性执行计算,但是无法从学生数组访问该属性.目前,我正在尝试使用以下代码获取分数的总和:

I have an object called student, with two properties, name and score. I am trying to perform calculations using the score property but am having trouble accessing the property from the array of students. Currently, I'm trying to get the sum of the scores with the following code:

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

这将返回一个未定义的值,并在Firefox中导致显示怪异.我似乎找不到错误.

This returns an undefined value and causes display weirdness in firefox. I can't seem to find the error.

有没有办法只是简单地访问参数(即 var myVar = myArray.myObject.myProperty; )?

Is there no way to just access parameters simply, (i.e. var myVar = myArray. myObject.myProperty;)?

推荐答案

我认为您对

I think you have a misunderstanding about how reduce works. For each element in the array, it executes the provided function. The first argument is an "accumulator"; something that's passed along as each element is visited (actually, it's the return value of the function from the last element, but it's usually used as an accumulator). The second argument is the element being visited. So what I think you want is this:

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

调用 reduce 时,可以提供累加器的初始值(否则,它将采用第一个元素的值,并且访问从第二个元素开始).在这里,我们为对象提供了一个 sum 属性设置为零的对象.

When you invoke reduce, you can provide the initial value of the accumulator (otherwise it takes on the value of the first element, and the visitation starts with the second element). Here, we provide an object with a sum property set to zero.

如果您只需要求和(不是具有 sum 属性的对象),则它甚至可以更简单:

If all you want is the sum (not an object with a sum property), it can be even simpler:

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

这篇关于减少返回未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆