js-array .reduce返回NaN而不是计算值 [英] js - array .reduce returns NaN instead of calculated value
问题描述
我正在编写一个简单的reduce函数:
I am writing a simple reduce function:
var tiles = [
{
"date": "2017-11-26",
"cloudCoverage": 92.2,
"area": 12055600804
},
{
"date": "2017-11-26",
"cloudCoverage": 92.78,
"area": 12055600804
},
{
"date": "2017-11-26",
"cloudCoverage": 97.29,
"area": 11609327018
}
]
function selectDateTile(tiles) {
return tiles.reduce((tile, currentPick) => {
console.log('tileArea: ', tile.area, 'currentPick area: ', currentPick.area)
return tile.area + currentPick.area
});
}
console.log(selectDateTile(tiles))
我希望它记录对象的实际值以及所有面积的总和:
I would expect it to log the actual values of the objects, and the sum of all the areas:
"tileArea:" 12055600804"currentPick区域:" 12055600804"tileArea:"12055600804"currentPick area:" 24111201608 ...
"tileArea: " 12055600804 "currentPick area: " 12055600804 "tileArea: " 12055600804 "currentPick area: " 24111201608 ...
但是我在jsbin中获得的控制台输出是:
But the console output I am getting in jsbin is:
"tileArea:" 12055600804"currentPick区域:" 12055600804"tileArea:"未定义的"currentPick区域:" 11609327018 NaN
"tileArea: " 12055600804 "currentPick area: " 12055600804 "tileArea: " undefined "currentPick area: " 11609327018 NaN
我在做什么错了?
推荐答案
请记住,传递给您的回调的第一个参数是累加器,并且您的回调应该返回该累加器的更新版本,然后在下一个版本中使用称呼.因此, tile
只会是 first 调用中数组中的一个条目;之后,它将成为您的回调返回的任何内容.
Remember that the first argument passed to your callback is the accumulator, and your callback is supposed to return updated version of that accumulator, which is then used on the next call. So tile
will only be an entry from the array on the first call; after that, it will be whatever your callback returns.
如果要汇总 area
属性,则要为累加器提供一个初始值( reduce
的第二个参数),然后使用它作为值,而不是对象:
If you're looking to sum up the area
properties, you want to supply an initial value for the accumulator (the second argument to reduce
) and then use it as a value, not an object:
function selectDateTile(tiles) {
return tiles.reduce((sum, currentPick) => { // <== Note `sum` parameter
return sum + currentPick.area; // <== Using `sum`
}, 0); // <== 0 as initial value
}
实时示例:
var tiles = [
{
"date": "2017-11-26",
"cloudCoverage": 92.2,
"area": 12055600804
},
{
"date": "2017-11-26",
"cloudCoverage": 92.78,
"area": 12055600804
},
{
"date": "2017-11-26",
"cloudCoverage": 97.29,
"area": 11609327018
}
];
function selectDateTile(tiles) {
return tiles.reduce((sum, currentPick) => { // <== Note `sum` parameter
return sum + currentPick.area; // <== Using `sum`
}, 0); // <== 0 as initial value
}
console.log(selectDateTile(tiles));
您可以编写您的回调,以便它检测到是否将其作为第一个参数或累加器传递给条目,但不必要地使代码复杂化.
You could write your callback so that it detected whether it was passed an entry as the first parameter or the accumulator, but it unnecessarily complicates the code.
这篇关于js-array .reduce返回NaN而不是计算值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!