1、实现数组去重
第一种:Set方法
let arr = [1, 4, 1, 4,6 ,1 ,true, true, "1", "2", "1"]
function fn1(arr) {
return Array.from(new Set(arr));
}
// 结果 [1, 4, 6, true, "1", "2"]
第二种:双重循环 + splice
function fn2 (arr) {
let len = arr.length;
for(let i = 0; i < len; i++) {
for(let j = i + 1; j < len; j++) {
if(arr[i] == arr[j]) {
arr.splice(j, 1);
j--; // 提高效率
len--;
}
}
}
return arr;
}
// 结果: [1, 4, 6, "2"] 不能对布尔值判断
第三种:indexOf去重
function fn3 (arr) {
let len = arr.length;
let res = [];
for(let i = 0; i < len; i++) {
if(res.indexOf(arr[i]) === -1) {
res.push(arr[i])
}
}
return res;
}
第四种:includes去重
function fn4 (arr) {
let len = arr.length;
let res = [];
for(let i = 0 ; i < len; i++) {
if(!res.includes(arr[i])) {
res.push(arr[i])
}
}
return res;
}
第五种:filter去重
function fn5 (arr) {
return arr.filter((item, index) => {
return arr.indexOf(item) === index;
})
}
第六种:Map去重
function fn6 (arr) {
let res = [];
let len = arr.length;
const map = new Map();
for(let i = 0; i < len; i++) {
if(!map.has(arr[i])) {
map.set(arr[i], true);
res.push(arr[i])
}
}
return res;
}
2、实现数组扁平化
第一种:flat方法实现
let arr = [1,2,[3,4]];
let res = arr.flat();
console.log(res); // [1,2,3,4]
第二种:reduce方法实现
let arr = [1,2,[3,4], [5,6]];
function fn7 (arr) {
return arr.reduce((pre, cur) => {
return pre.concat(Array.isArray(cur) ? fn7(cur) : cur);
}, [])
}
//结果: [1, 2, 3, 4, 5, 6]
第三种:循环遍历
const arr = [1, [2, [3, [4, 5]]], 6];
let res5 = [];
function fn8 (arr) {
console.log(arr.length)
let len = arr.length;
for(let i = 0; i < len; i++) {
if(Array.isArray(arr[i])) {
fn8(arr[i]);
}else {
res5.push(arr[i]);
}
}
}
fn8(arr);
// 结果:[1,2,3,4,5,6]
3、手撸防抖
// 防抖函数
function debounce(fn, time) {
let timeout = null;
return function () {
clearTimeout(timeout);
timeout = setTimeout(() => {
fn.apply(this, arguments)
}, time);
}
}
4、手撸节流
// 节流函数
function throttle (fn, time) {
let flag = true;
return function () {
if(!flag) return ;
flag = false;
setTimeout(() => {
fn.apply(this, arguments);
flag = false;
}, time);
}
}