-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharrayPrototypeExtend.js
More file actions
92 lines (86 loc) · 1.84 KB
/
arrayPrototypeExtend.js
File metadata and controls
92 lines (86 loc) · 1.84 KB
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
89
90
91
92
/**
* 实现数组原型的forEach方法
*/
Array.prototype.forEach2 = function(callback, thisArg) {
if (this === null) {
throw new TypeError('this is null or not defined')
}
if (typeof callback !== 'function') {
throw new TypeError(callback + 'is not a function')
}
const o = Object(this)
const len = o.length >>> 0
let k = 0
while (k < len) {
if (k in o) {
callback.call(thisArg, o[k])
}
k++
}
}
/**
* 测试forEach2用例
*/
let arr = new Array(1, 2, 3)
arr.forEach2((item) => {
console.log(item, '-item')
})
/**
* 实现数组原型的map方法
*/
Array.prototype.map2 = function(callback, thisArg) {
if (this === null) {
throw new TypeError('this is null or not defined')
}
if (typeof callback !== 'function') {
throw new TypeError(callback + 'is not a function')
}
const o = Object(this)
const len = o.length >>> 0
let k = 0
let res = []
while (k < len) {
if (k in o) {
res[k] = callback.call(thisArg, o[k])
}
k++
}
return res
}
/**
* 测试forEach2用例
*/
let arr1 = new Array(1, 2, 3)
let newArr1 = arr.map2((item) => `${item}-${item}`)
console.log('测试forEach2用例', newArr1)
/**
* 实现数组原型的filter方法
*/
Array.prototype.filter2 = function(callback, thisArg) {
if (this === null) {
throw new TypeError('this is null or not defined')
}
if (typeof callback !== 'function') {
throw new TypeError(callback + 'is not a function')
}
const o = Object(this)
const len = o.length >>> 0
let k = 0
let res = []
while (k < len) {
if (k in o) {
const result = callback.call(thisArg, o[k])
if (result) {
res.push(o[k])
}
}
k++
}
return res
}
/**
* 测试filter2用例
*/
let arr2 = new Array(1, 2, 3)
let newArr2 = arr.filter2((item) => item > 2)
console.log('测试filter2用例', newArr2)