Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/379.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 array.reduce()的正确用户_Javascript_Arrays_Reduce - Fatal编程技术网

Javascript array.reduce()的正确用户

Javascript array.reduce()的正确用户,javascript,arrays,reduce,Javascript,Arrays,Reduce,下面我概述了freeCodeCamp上一个问题的解决方案,我想检查一下我对array.reduce()工作原理的逻辑/理解 在遍历数组中的每个数字之后,它使用push()将5推入bigArray[] bigArray.push(arr[i].reduce(function(a, b){return Math.max(a, b);})); //arr[0] is now arr[4, 5, 1, 3] arr[0].reduce(function(a, b){return Math.max(0,

下面我概述了freeCodeCamp上一个问题的解决方案,我想检查一下我对array.reduce()工作原理的逻辑/理解

在遍历数组中的每个数字之后,它使用push()将5推入bigArray[]

bigArray.push(arr[i].reduce(function(a, b){return Math.max(a, b);}));
//arr[0] is now arr[4, 5, 1, 3]
arr[0].reduce(function(a, b){return Math.max(0, 4);}));
//Math.max returns 4
arr[0].reduce(function(a, b){return Math.max(4, 5);}));
//Math.max returns 5
arr[0].reduce(function(a, b){return Math.max(5, 1);}));
//Math.max returns 5    
arr[0].reduce(function(a, b){return Math.max(5, 3);}));
//Math.max returns 5
在上述逻辑之后,5将“push()”放入bigArray,bigArray=[5]

只是检查我的逻辑和对自己代码的理解

只是检查我的逻辑和对自己代码的理解

需要稍作修改

在第一次迭代中,比较不是在
0
4
之间,而是在
4
5
之间

请看一下此演示

[4,5,1,3].reduce(函数(a,b){
控制台日志(a,b)
返回Math.max(a,b);

})
arr
一个数组吗?看参数很明显。这更适合我错过代码块的最后一行“a是初始值,是0,因为我没有传递初始值”这是错误的啊,我明白了,谢谢澄清。它是n-1,或者在本例中只有3次迭代,因为4和5被传递到“a”和“b”。
then a = 4 and b = 5, then Math.max = 5
then a = 5 and b = 1, then Math.max = 5
then a = 5, and b = 3, then Math.max = 5
bigArray.push(arr[i].reduce(function(a, b){return Math.max(a, b);}));
//arr[0] is now arr[4, 5, 1, 3]
arr[0].reduce(function(a, b){return Math.max(0, 4);}));
//Math.max returns 4
arr[0].reduce(function(a, b){return Math.max(4, 5);}));
//Math.max returns 5
arr[0].reduce(function(a, b){return Math.max(5, 1);}));
//Math.max returns 5    
arr[0].reduce(function(a, b){return Math.max(5, 3);}));
//Math.max returns 5