js.md

数组扁平化

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
// 我有个问题, 扁平化数组我这样写 没办法控制住depth
// 求一个优雅的方案, 解决扁平化数组时depth层级API问题
const flat = (arr, depth = 1) => {
while(depth > 0) {
arr = arr.reduce((sum, cur) => {
if(isType(cur) === 'Array') {
// 主要是这一段, 如果不使用递归, 那么就是根据depth控制, 扁平化的深度
sum = sum.concat(flat(cur))
} else {
sum.push(cur)
}
return sum
}, [])
depth--
}
return arr
}


const isType = (value) => {
return Object.prototype.toString.call(value).match(/(?<= )\w+/)[0]
// String Number Null Undefined Object Date RegExp Symbol Boolean Function Array
}

flat([1, 2, 3, [1]], 1)

数组根据Number分片

1
2
3
4
5
6
7
8
9
10
11
function chunkArrayInGroups(arr, size) {
// Break it up.
return arr.reduce((sum, cur, index) => {
if(index % size === 0) {
sum.push([cur])
} else {
sum[sum.length - 1].push(cur)
}
return sum
}, [])
}

constructor 属性可以被重写,作为判定父级的方法并不可靠.

isPrototypeOf: 判断原型链来自哪里?

注意,当我们使用原型的继承时, 我们要注意, 往prototype上面不可以使用字面量的方式去增加属性,但是你可以自己写一个方法, 以字面量作为参数传入.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

function Animal() { }
Animal.prototype.eat = function() { console.log("nom nom nom"); };

function Dog() { }

// 请把你的代码写在这条注释以下
Dog.prototype = Object.create(Animal.prototype)
Dog.prototype.constructor = Dog
Dog.prototype.bark = () => {
console.log('Woof!')
}
// 请把你的代码写在这条注释以下

let beagle = new Dog();

beagle.eat(); // 应该输出 "nom nom nom"
beagle.bark(); // 应该输出 "Woof!"