Created
October 8, 2012 05:16
-
-
Save sofish/3850834 to your computer and use it in GitHub Desktop.
array 的 reduce 方法好奇怪
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var arr = [1,2,3,4,5,6,7,8,9]; | |
arr.reduce(function(prev, cur, i, index){ | |
// 奇葩 | |
console.log(prev,cur,i,index, arr[--i] === prev) | |
}) | |
arr.reduce(function(prev, cur, i, index){ | |
// 正常 | |
console.log(prev,cur,i,index, arr[--i] === prev) | |
return cur; | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
第一个reduce的callback没有返回值,相当于是undefined了
从MDN上搬个reduce的实现
第一次while循环的时候curr=this0,所以输出结果中获取到的prev就是数组的第一个元素, 而后所有循环的prev都是前一次调用callback的返回值, 而第一个arr.reduce中的callback没有返回值,所以就全都是undefiend。