首页

  • 首页
  • 友链
  • 标签
  • 关于

封装一些数组的方法

白羊座的梦 发布于 2020-03-09

封装一些数组api的方法

数组forEach方法

1
2
3
4
5
6
7
8
Array.prototype.myforEach = function(cb){
//this --> arr
for(let i=0;i<this.length;i++){
cb(this[i],i)
}

}
arr.myforEach(arr);

数组filter方法

1
2
3
4
5
6
7
8
9
10
Array.prototype.myFilter = function(cb){
//this --> arr
let arr = []
for(let i=0;i<this.length;i++){
if(cb(this[i],i)){ //如果回调函数的返回值为真
arr.push(cb(this[i],i))
}
}
return arr
}

数组map方法

1
2
3
4
5
6
7
Array.prototype.myMap = function(cb){
let arr = []
for(let i=0;i<this.length;i++){
arr.push(cb(this[i],i))
}
return arr
}

数组map方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
Array.prototype.myReduce = function (cb, value) {
// let result = 0;
if (value||value===0) {//如果传递了第二个参数
for(let i = 0; i < this.length; i++){
// result = cb(i === 0 ?value : result, this[i])
value = cb(value, this[i])
}
} else {
for (let i = 0; i < this.length - 1; i++) {
/*
result += cb(this[i],this[i+1])
i=0 result 3
i=1 result 3+5=8
i=2 result 8+7=15
i=3 result 15+9=24

result = cb(i===0?this[i]:result,this[i+1])
i=0 result 3
i=1 result 3+3=6
i=2 result 6+4=10
i=3 result 10+5=15
*/

value = cb(i === 0 ? this[i] : value, this[i + 1])
}
}
return value
}

let arr1 = [1, 2, 3, 4, 5] //15
let arr2 = [
{age:20},
{age:30},
{age:40}
]
let result = arr2.myReduce(function (pre, next) {
/*
pre 1 next 2
pre 1+2 next 3
pre 1+2+3 next 4
pre 1+2+3+4 next 5
*/

// console.log(pre, next)
// return pre + next
return pre+next.age
},0)
console.log(result)
Newer
封装call,apply,bind方法
Older
函数节流和防抖封装

© 2020 白羊座的梦

Powered by Hexo Theme - flex-block