forked from zzzzzhowie/practical-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap.js
More file actions
39 lines (33 loc) · 1.07 KB
/
Copy pathmap.js
File metadata and controls
39 lines (33 loc) · 1.07 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
// ES5循环实现map
const selfMap = function (fn, context) {
let arr = Array.prototype.slice.call(this)
let mappedArr = []
for (let i = 0; i < arr.length; i++) {
// 判断稀疏数组的情况
if (!arr.hasOwnProperty(i)) continue;
mappedArr.push(fn.call(context, arr[i], i, this))
}
return mappedArr
}
// reduce实现map
const selfMap2 = function (fn, context) {
let arr = Array.prototype.slice.call(this)
return arr.reduce((pre, cur, index) => {
return [...pre, fn.call(context, cur, index, this)]
}, [])
}
Array.prototype.selfMap || (Object.defineProperty(Array.prototype, 'selfMap', {
value: selfMap,
enumerable: false,
configurable: true,
writable: true
}))
Array.prototype.selfMap2 || (Object.defineProperty(Array.prototype, 'selfMap2', {
value: selfMap2,
enumerable: false,
configurable: true,
writable: true
}))
let arr = ['z', 'h', 'l']
console.log(arr.selfMap(item => item + "1"))
console.log(selfMap2.call({0:'a',1:'b',length:2}, item => item + "1")) // map 方法同样支持类数组