js中forEach、map、filter、some、every函数的简易实现

forEach跟map函数区别在于map有返回值,forEach无返回值
map跟filter函数的区别在于filter会过滤值,而map直接返回值
filter跟some的区别在于some有符合的数据就返回true,而filter是返回值
some跟every的区别在于every要所有的数据都满足才返回true,而some是一个满足就返回true
上面几个函数的实现都差不多,只是某一小点不一样,其实原理都一样

//forEach
Array.prototype.myForEach = function(fn){
	if(this === null){
		throw new Error('对象为空')
	}
	if(typeof fn !== 'function'){
		throw new Error('请传入函数!')
	}
	var o = this,
		len = o.length >>> 0,
		_this = arguments[1] || window; 
	for(var i = 0; i < len; i++){
		fn.call(_this, o[i], i, o);
	}
}
//map
Array.prototype.myMap= function(fn){
	if(this === null){
		throw new Error('对象为空')
	}
	if(typeof fn !== 'function'){
		throw new Error('请传入函数!')
	}
	var o = this,
		len = o.length >>> 0,
		_this = arguments[1] || window,
		res = []; 
	for(var i = 0; i < len; i++){
		res.push(fn.call(_this, o[i], i, o));
	}
	return res;
}
//filter
Array.prototype.myFilter= function(fn){
	if(this === null){
		throw new Error('对象为空')
	}
	if(typeof fn !== 'function'){
		throw new Error('请传入函数!')
	}
	var o = this,
		len = o.length >>> 0,
		_this = arguments[1] || window,
		res = []; 
	for(var i = 0; i < len; i++){
		if(fn.call(_this, o[i], i, o)){
			res.push(o[i]);
		}
	}
	return res;
}
//some
Array.prototype.mySome= function(fn){
	if(this === null){
		throw new Error('对象为空')
	}
	if(typeof fn !== 'function'){
		throw new Error('请传入函数!')
	}
	var o = this,
		len = o.length >>> 0,
		_this = arguments[1] || window;
	for(var i = 0; i < len; i++){
		if(fn.call(_this, o[i], i, o)){
			return true;
		}
	}
	return false;
}
//every
Array.prototype.myEvery= function(fn){
	if(this === null){
		throw new Error('对象为空')
	}
	if(typeof fn !== 'function'){
		throw new Error('请传入函数!')
	}
	var o = this,
		len = o.length >>> 0,
		_this = arguments[1] || window;
	for(var i = 0; i < len; i++){
		if(!fn.call(_this, o[i], i, o)){
			return false;
		}
	}
	return true;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值