forEach和map都是js数组的循环方法,都是循环数组,但是又有些许不同
相同点:
- 都是循环遍历数组中的每一项;
- 每次执行匿名函数都支持三个参数,参数分别为item(当前每一项),index(索引值),arr(原数组)
- 都不改变原始数组;
不同点:
forEach无返回值,map有返回值
他们都是js数组的方法,既然是是方法,那就必然有方法的三要素:方法名、参数和返回值
forEach的三要素分别是 forEach方法名、一个匿名函数作为参数,无返回值
map的 三要素是 map方法名,一个匿名函数作为参数,一个数组回值‘
因此forEach不能使用break来终止循环,因为在使用函数中是不能使用循环的
forEach实现原理应该类似如下
Array.prototype.ForEach=function (callback){
for (let i = 0; i < this.length; i++) {
callback(this[i],i,this)
}
}
同理map
Array.prototype.Map=function (callback){
let returnList=[];
for (let i = 0; i < this.length; i++) {
returnList.push(callback(this[i],i,this))
}
return returnList;
}
思路是在方法内部实现循环,通每循环执行一次匿名函数
基于此种思路可以实现类似删除数组中符合的一项
Array.prototype.Remove=function (prefunc){
for (let i = 0; i <this.length ; i++) {
let result=prefunc(this[i],i);
// if(result){
if ( result && typeof (result)=="boolean"){
this.splice(i,1);
i--;
}
}
}
使用方法
let arr=[{name:"zhangsan",age:20},{name:"lisi",age:25},{name:"wanger",age:23}];
arr.Remove((item)=>{return item.age==20})
console.log(arr)
输出
[ { name: 'lisi', age: 25 }, { name: 'wanger', age: 23 } ]
同理实现类似Sort的功能
Array.prototype.Sort=function (prefunc){
if (this.length==0){
return this;
}
for (var i = 0; i < this.length - 1; i++) {
for (var j = 0; j <this.length - i - 1; j++) {
let sort=(prefunc && typeof(prefunc)=="function") ? prefunc(this[j],this[j+1])>0 :this[j]>this[j+1]
if (sort){
var temp = this[j];
this[j] = this[j + 1];
this[j + 1] = temp
}
}
}
}