-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path数组一些常用的方法实现.js
89 lines (78 loc) · 1.89 KB
/
数组一些常用的方法实现.js
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
Array.prototype.forEach = function (cb, context = undefined) {
let arr = this.slice()
let len = arr.length
for (let i = 0; i < len; i++) {
if (i in arr) {
cb.call(context, arr[i], i, arr)
}
}
}
Array.prototype.push = function () {
for(let i = 0; i< arguments.length; i++) {
this[this.length] = arguments[i]
}
return this.length
}
Array.prototype.pop = function(){
let len = this.length
if(len === 0) return
let value = this[this.length - 1]
this.length -= 1
return value
}
Array.prototype.shift = function() {
let len = this.length
if(len === 0) return
let value = this[0]
var newArr = []
for(let i = 1; i<len; i++) {
newArr.push(this[i])
}
this = newArr
return value
}
Array.prototype.map = function (cb, context = undefined) {
let arr = this.slice()
let len = arr.length
let res = []
for (let i = 0; i < len; i++) {
res[i] = cb.call(context, arr[i], i, arr)
}
return res
}
Array.prototype.myReduce = function (cb, initData) {
let arr = this, len = arr.length
let res = initData || arr[0]
let startIndex = initData ? 0 : 1
for (let i = startIndex; i < len; i++) {
res = cb(res, arr[i], i, arr)
}
return res
}
Array.prototype.mapByReduce = function (cb, context = null) {
return arr.reduce((pre, curr, index, arr) => {
let res = cb.call(context, curr, index, arr)
return [...pre, res]
},[])
}
Array.prototype.filter = function (cb, context=undefined) {
let arr = this.slice()
let len = arr.length
let res = [], newIndex=0
for (let i = 0; i < len; i++) {
let flag = cb.call(context, arr[i], i, arr)
if (flag) {
console.log(i, flag)
res[newIndex++] = arr[i]
}
}
return res
}
Array.prototype.find = function (cb, context) {
let arr = this.slice()
let len = arr.length
for (let i = 0; i < len; i++) {
let res = cb.call(context, arr[i], i, arr)
if(res) return arr[i]
}
}