1.Promise
class Promise {
constructor(executor) {
this.status = "pending";
this.value = undefined;
let resolve = result => {
if (this.status !== "pending") return;
this.status = "resolved";
this.value = result;
}
let reject = reason => {
if (this.status !== "pending") return;
this.status = "rejected";
this.value = reason;
}
try {
executor(resolve, reject)
} catch (error) {
reject(error)
}
}
then(onFulfilled, onRejected) {
if (this.state === 'fulfilled') {
onFulfilled(this.value);
};
if (this.state === 'rejected') {
onRejected(this.reason);
};
}
}
2.数组扁平化处理
es6
let arr = [1, [2, [3, 4]]]
arr.flat(Infinity)
递归
let arr = [1, [2, [3, 4]]]
function flatter(arr,result = []){
for(let i = 0
if(Array.isArray(arr[i])){
flatter(arr[i],result)
}else{
result.push(arr[i])
}
}
return result
}
console.log(flatter(arr))
reduce 方法
let arr = [1, [2, [3, 4]]];
function flatter(arr){
return arr.reduce((prev,next)=>{
return prev.concat(Array.isArray(next)?flatter(next):next)
},[])
}
console.log(flatter(arr))
3.深拷贝
const cloneDeep = (obj) => {
if (obj === null || typeof obj !== 'object') return obj
let copy = Array.isArray(obj) ? [] : {}
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
copy[key] = cloneDeep(obj[key])
}
}
return copy
}