简单实现map和reduce

Array.prototype.myreduce = function(fn){
	if(typeof fn !== 'function'){
		throw new error('argument is not a function')
	}else{
		if(this.length === 0){
			throw new error('Reduce of empty array with no initial value')
		}
		let res = this[0]
		for(let i = 1;i<arr.length;i++){
			res = fn(res,arr[i])
		}
		return res
	}

}
Array.prototype.mymap = function(fn){
	if(typeof fn !== 'function'){
		throw new error('argument is not a function')
	}else{
		let res = []
		for(let item of this){
			res.push(fn(item))
		}
		return res
	}
}

你可能感兴趣的:(js)