Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 47a7886

Browse files
committed
feat: add reduce map implemention
1 parent 6d703d8 commit 47a7886

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

‎js/reduce_map.js‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/*
2+
* @Author: Chacha
3+
* @Date: 2022年05月06日 17:15:45
4+
* @Last Modified by: Chacha
5+
* @Last Modified time: 2022年05月06日 19:52:19
6+
*/
7+
8+
/**
9+
* map: 遍历数组的每一项,并执行回调函数的操作,返回一个对每一项进行操作后的新数组。
10+
*
11+
* reduce: 对数组累积执行回调函数,返回最终计算结果。
12+
*
13+
* @param {*} callback
14+
* @param {*} ctx
15+
* @returns
16+
*
17+
*/
18+
Array.prototype.map2 = function (callback, ctx = null) {
19+
if (typeof callback !== "function") {
20+
throw new Error("callback must be a function");
21+
}
22+
23+
return this.reduce(
24+
(result, cur, index, array) =>
25+
result.concat(callback.call(ctx, cur, index, array)),
26+
[]
27+
);
28+
};
29+
30+
let arr = [1, 2];
31+
let arr1 = arr.map2(
32+
function (it, i, array) {
33+
console.log(it, i, array, this);
34+
return it * 2;
35+
},
36+
{ name: "Chacha" }
37+
);
38+
39+
console.log("====================================");
40+
console.log(arr1);
41+
console.log("====================================");

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /