手写Array.prototype.reduce(),及使用详细讲解

本文详细解析了JavaScript中Array.prototype.reduce()方法的工作原理,并通过实例演示如何手动实现该方法,包括其参数传递机制和使用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

手写Array.prototype.reduce(),及详细讲解

Array.prototype.reduce()的参数是一个回调函数

let arr = [10,20,30,40,50,60];
let result = arr.reduce((result,item,index)=>{
	console.log(result,item,index)
	return '我爱你'
})
//会输出:
//1:10,20,1
//2:'我爱你',30,2
//3:'我爱你',40,3
//4:'我爱你',50,4
//5:'我爱你',60,5
//所以:reduce中的回调函数的第一个参数(result)是上一次执行回调函数的返回值
  • reduce中的第二个参数是,初始化回调函数第一个参数的值,如果没有传入,那么回调函数的第一个参数是数组第一项
  • reduce中的回调函数的第一个参数(result)是上一次执行回调函数的返回值
let arr = [10,20,30,40,50,60];
let result = arr.reduce((result,item,index)=>{
	console.log(result,item,index)
	return '我爱你'
},10000)
//会输出:
//1:10000,10,0
//2:'我爱你',20,1
//3:'我爱你',30,2
//4:'我爱你',40,3
//5:'我爱你',50,4
//5:'我爱你',60,5
//所以:reduce中的回调函数的第一个参数(result)在有reduce第二个参数传入的情况下,就是那个reduce的第二个参数,没有就是数组第一项

手写reduce()

Array.prototype.myReduce = function (callback,chushiz){
	//this------>就是调用myReduce的那个数组
	//callback-------->就是那个回调函数
	let result,index
	if (chushiz){
		result = chushiz;
		index = 0
	}else {
		result = this[0];
		index = 1
	}
	for(;index<this.length;index++){
		result = callback(result,this[index],index);
		//循环数组,执行回调函数,获得回调函数的返回值,将返回值赋值为result,
		//就改变了回调函数的第一个参数
	}
	return result
}

验证,以累加数组每一项和为例

Array.prototype.reduce

let arr = [10,20,30,40]
let result = arr.reduce((result,item,index)=>{
   return result + item;
})
console.log(result); //100

Array.prototype.myReduce

Array.prototype.myReduce = function (callback,chushiz){
	//this------>就是调用myReduce的那个数组
	//callback-------->就是那个回调函数
	let result,index
	if (chushiz){
		result = chushiz;
		index = 0
	}else {
		result = this[0];
		index = 1
	}
	for(;index<this.length;index++){
		result = callback(result,this[index],index);
		//循环数组,执行回调函数,获得回调函数的返回值,将返回值赋值为result,
		//就改变了回调函数的第一个参数
	}
	return result
}
let arr = [10,20,30,40]
let result = arr.myReduce((result,item,index)=>{
   return result + item;
})
console.log(result); //100
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值