Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript中的数组Reduce在第一次求和后开始返回NaN_Javascript_Arrays - Fatal编程技术网

javascript中的数组Reduce在第一次求和后开始返回NaN

javascript中的数组Reduce在第一次求和后开始返回NaN,javascript,arrays,Javascript,Arrays,我不明白为什么array.reduce会在第一次传递时返回正确的和,但在下一次传递时返回NaN。有人能解释一下为什么会发生这种情况吗 编辑-我需要解释一下,我正在尝试创建一个新数组,每个数组都会添加到以前的值中。所以 [1,2,3,4] 变成 [1,3,6,10] 现在它出来了 [1,3,楠,楠] 工作小提琴 你想用数字(数组)做什么?如果您试图将数组转换为数字,您将遇到一个问题,因为这是一个无意义的转换(就像苹果转换为表)。要获取数组的最后一个添加数并求和: var numbers = [1

我不明白为什么array.reduce会在第一次传递时返回正确的和,但在下一次传递时返回NaN。有人能解释一下为什么会发生这种情况吗

编辑-我需要解释一下,我正在尝试创建一个新数组,每个数组都会添加到以前的值中。所以

[1,2,3,4] 变成 [1,3,6,10]

现在它出来了 [1,3,楠,楠]

工作小提琴


你想用
数字(数组)
做什么?如果您试图将数组转换为数字,您将遇到一个问题,因为这是一个无意义的转换(就像苹果转换为表)。要获取数组的最后一个添加数并求和:

var numbers = [1, 2, 3, 4];

function getSum(total, currentValue, currentIndex, arr) {
   var newVal = currentValue; // The new value is the current number
   if (currentIndex > 0) { // If we are in the second position or more, sum the last value, which is the curent position minus one.
       newVal += total[currentIndex-1];
   }
   total.push(newVal);
   return total;
}

var display = numbers.reduce(getSum, []);
document.getElementById("show").innerHTML = display

getSum
中,变量
total
是一个数字数组。代码
Number(total)
产生了
NaN
。这个函数想要实现什么?好的,我认为total是上一个函数的值-这是一个好的开始,谢谢,我编辑了更多信息。
var total=0,display=numbers.map(v=>total+=v)只是一些思考的食物W感谢Thomas,它使用的代码比使用reduce少得多。非常非常有趣!现在我对这两个都有了更深的理解!我试图消化你的评论,但我忘了解释我在做什么,我用更多的信息编辑了这篇文章。我正试图用上一个数组中的值创建一个新数组total@user3869231更新:那是个老板!谢谢:)@user3869231 np:P
var numbers = [1, 2, 3, 4];

function getSum(total, currentValue, currentIndex, arr) {
   var newVal = currentValue; // The new value is the current number
   if (currentIndex > 0) { // If we are in the second position or more, sum the last value, which is the curent position minus one.
       newVal += total[currentIndex-1];
   }
   total.push(newVal);
   return total;
}

var display = numbers.reduce(getSum, []);
document.getElementById("show").innerHTML = display