map find filter internal analog array implementation

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/nightwishh/article/details/101633768

1. Array map () method is implemented:

遍历数组数据并将其回调,再将所有返回值添加到新数组中
Array.prototype.mymap = function(callback) {
	let newArr = []; 
	for (let i = 0; i < this.length; i++) {
		let item = this[i];
		let index = i;
		let array = this;
		let result = callback(item, index, array);
		newArr.push(result)
	}
	return newArr
}

2. Array find () method is implemented:

遍历数组数据并将其回调,判断回调只要有一个结果为true则返回
Array.prototype.myfind=function(callback){
	for(let i=0;i<this.length;i++){
		if(callback(this[i],i,this)){
			let x=callback(this[i])
			return this[i]
		}
	}
}

3. Array filter () method is implemented:

遍历数组数据并将其回调,过滤出为true的结果添加至新数组中并返回
Array.prototype.myFilter=function(callback){
	let newArr=[]
	for(let i=0;i<this.length;i++){
		callback(this[i])
		if(callback(this[i],i,this)){
			newArr.push(this[i])
		}
	}
	return newArr
}

Guess you like

Origin blog.csdn.net/nightwishh/article/details/101633768
Recommended