写一个 对象的深拷贝
深拷贝
function deepClone(obj) {
/*
基本类型:直接赋值 string null undefined number boolean symobl
引用类型 :属性递归array object
*/
if (typeof obj !== "object" || obj == null) {
return obj
}
let newObj = Array.isArray(obj) ? [] : {};
for (let i in obj) {
if (obj.hasOwnProperty(i)) {
newObj[i] = deepClone(obj[i]);
}
}
return newObj;
}
防抖
function debobunce(handler, time) {
let timer = null;
clearTimeout(timer)
return function() {
timer = setTimeout(function() {
let that = this;
let args = arguments;
handler.apply(that, args)
}, time)
}
}
节流
function throttle(handler, time) {
let lastTime = 0;
return function() {
let nowTime = new Date().getTime();
if (nowTime - lastTime > time) {
handler.apply(this, arguments);
lastTime = nowTime;
}
}
}
使用setTimeout实现setInterval
function timeFun() {
let timer = setTimeout(function() {
timeFun();
console.log("do it")
clearTimeout(timer)
}, 1000)
}
实现Array.protoType.flat
flat的特性:
1: 该方法是将数组拉平,变成一维数组,返回一个新数组,对原数组没有影响
2:不传参数时,只“拉平一层”,可以传入一个整数,表示想拉平的层数
3:传入<=0的数时,不拉平
4:Infinity关键字作为参数时,无论多少层,都会转化为一维数组
5:如果原数组有空位, Array.prototype.flat()会跳过空位
判断元素是数组的方案
arr instanceof Array
arr. constructor === Array
Object.prototype.toString.call(arr) ===[object Array]
Array.isArray(arr)
{
Array.prototype.flat2 = flatArray;
function flatArray(num = 1) {
if (!Number(num) || Number(num) < 0) {
return this;
}
let arr = [];
this.forEach(item => {
if (Array.isArray(item)) {
arr = arr.concat(item.flat2(--num))
} else {
arr.push(item)
}
})
return arr
}
let arr = [1, 2, 4, 4, , , 5, [1, 2, 3]];
console.log(arr.flat2(3));
console.log(arr.flat(3));
}