reduce-类数组转数组-calculate-json深度-数组扁平化
# reduce-类数组转数组-calculate-json深度-数组扁平化
// reduce
Array.prototype.myReduce = function(fn, initialValue = undefined) {
// 处理数组类型异常
if (this === null || this === undefined) {
throw new TypeError("Cannot read property 'reduce' of null or undefined");
}
let accumular;
let start = 0;
if (initialValue === undefined) {
accumular = this[0]
} else {
accumular = initialValue
}
for (let i = start; i < this.length; i++) {
if (initialValue === undefined && i + 1 === this.length) {
break;
}
accumular = fn(
accumular,
initialValue === undefined ? this[i + 1] : this[i],
i,
this
);
}
return accumular
};
let res = [1, 2, 3, 4, 5].myReduce((pre, cur, index, arr) => {
return pre + cur;
}, 3);
console.log(res);
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
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
/**
* 类数组转数组
*/
function transformArr() {
let arr = [...arguments];
let arr1 = Array.prototype.slice.call(arguments);
let arr2 = Array.from(arguments);
let arr3 = [];
let arr4 = new Array(...arguments);
for (let i = 0; i < arguments.length; i++) {
arr3.push(arguments[i]);
}
console.log(arr);
console.log(arr1);
console.log(arr2);
console.log(arr3);
console.log(arr4);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Calculate {
constructor(value) {
this.state = "pending";
this.value = value;
}
add(value) {
if (this.state === "pending") {
return new Calculate(value + this.value);
} else {
throw "error";
}
}
subtract(value) {
if (this.state === "pending") {
return new Calculate(this.value - value);
} else {
throw "error";
}
}
result() {
return {
value: this.value,
state: "done",
};
}
}
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
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
function getDepth(obj) {
let deep = 1;
function myDeep(obj, num) {
for(let key in obj) {
if (obj.hasOwnProperty(key)) {
if (typeof obj[key] === 'object') {
myDeep(obj[key], num+1)
} else {
deep = Math.max(deep, num+1);
}
}
}
}
myDeep(obj, 1)
return deep
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 数组扁平化
*/
const arr = [1, [2, [3, [4, 5]]], 6];
const flat1 = arr.flat(Infinity); // 第一种方法
function flatArr(arr, res) {
for (let key of arr) {
if (key instanceof Array) {
flatArr(key, res);
} else {
res.push(key);
}
}
return res;
}
flatArr(arr, [])
function flatten2(arr) {
return arr.reduce(
(pre, cur) => pre.concat(cur instanceof Array ? flatten2(cur) : cur),
[]
);
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25