[英]Combining length of arrays, why is it returning NaN? JavaScript
Info: Hi you can see there are 4 arrays, and then an array with those arrays inside. 信息:嗨,您可以看到有4个数组,然后是其中包含这些数组的数组。 I'm using _.reduce to add up the length of the arrays.
我正在使用_.reduce来增加数组的长度。 I'm getting NaN when I call the function with the array of arrays.
当我使用数组数组调用函数时,我得到了NaN。 I would expect to get 19.
我希望得到19。
Why is this? 为什么是这样? Thanks for help
感谢帮助
var array1 = [[1],[2],[3],[4],[5]];
var array2 = ["a", "b"];
var array3 = [{name : "John"}, {age : 21}];
var array4 = [1,2,3,4,5,6,7,8,9,0];
var array5 = [array4, array3, array2, array1];
var arrayComboLength = function(array){
return _.reduce(array, function(a,b){
return a.length + b.length;
});
}
console.log(arrayComboLength(array5)); --> // NaN
The first argument of reduce
's callback is the accumulator. reduce
的回调的第一个参数是累加器。 You are accessing the length
of a number and that results in undefined
. 您正在访问数字的
length
,结果为undefined
。 And then you are adding undefined
to the numbers that are the lengths of the rest of the arrays which results in undefined
. 然后将
undefined
添加到作为其余数组长度的数字上,这将导致undefined
。
var arrayComboLength = function(array) {
return _.reduce(array, function(a, b) {
return a + b.length;
}, 0);
}
This is very close to the example given in the documentation http://underscorejs.org/#reduce 这与文档http://underscorejs.org/#reduce中给出的示例非常接近
The counting function will be recursively applied to all elements of the array. 计数函数将递归应用于数组的所有元素。 Recursively, so they will also be applied to the scalar values in array4, for example.
例如,递归地将它们也应用于array4中的标量值。 Scalar values don't have a length.
标量值没有长度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.