好吧,原来是源码抽取来的,应该是为了找到arr
中第一个值的索引
比如
arr = [1, 2, 3]
delete(arr[0])
0 in arr // false
1 in arr // true
因为把arr[0]
删掉了,arr
中第一个数字的索引值就变成1了,此时k = 1
了
因为当arguments.length != 2
的时候,意味着用户没提供reduce
的初始值,
所以就要找到arr
中的第一个有效值arr[k]
赋给value
作为初始值
题主你提供这个版本的实现应该是有bug
的,你自己试一下把你的Array.prototype.reduce
实现复制进console
,然后输入以下代码
arr = [1, 2, 3]
arr.reduce( (s, i) => s+i ) // 6
arr.reduce( (s, i) => s+i, 1 ) // 7
arr.reduce( (s, i) => s+i, 1, 2 ) // 6
然后就会发现,当arguments.length == 3
时,reduce
是会忽略你提供的初始值的
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…