数组去重
方法1:Set结构去重
这是ES6 提供了新的数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。
let arr = [2, 4, 5, 6, 2, 4, 9, 1, 9];
let result = [...new Set(arr)];
console.log(result);
方法2:indexOf()
遍历,将值添加到新数组,用indexOf()判断值是否存在,已存在就不添加,达到去重效果
let arr1 = [2, 4, 5, 6, 2, 4, 9, 1, 9, 1, 7, 8]
var result1 = []
arr1.map(item => {
if (result1.indexOf(item) === -1) {
result1.push(item);
}
})
console.log(result1);
数组扁平化
方法1:递归法
let arr = [1, [2, [3, 4]]]
const result = [];
const fn = (arr) => {
for (var i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
fn(arr[i]);
} else {
result.push(arr[i]);
}
}
}
fn(arr)
console.log(result);
方法2: 扩展运算符
function fn1(arr) {
while (arr.some(item => Array.isArray(item))) {
arr = [].concat(...arr);
console.log(arr);
}
return arr;
}
console.log(fn1(arr));
函数柯里化
经典面试题: add(1); // 1
add(1)(2) // 3
add(1)(2)(3) // 6
add(1)(2,3) //6
add(1,2)(3) // 6
function add1(x) {
return x
}
function add2(x, y) {
return x + y
}
function add3(x, y, z) {
return x + y + z
}
function kkCurrying(fn) {
function curried(...args) {
// 判断当前已经接受的参数的个数,可以判断参数本身需要接受的参数是否已经一致了
// 1.当已经传入的参数大于等于需要的参数时,就执行函数
if (args.length >= fn.length) {
return fn.apply(this, args);
}
else {
// 没有达到个数时,需要返回一个新的函数,继续来接受参数
function curried2(...args2) {
// 接收到参数后,需要递归调用curried
return curried.apply(this, args.concat(args2))
}
return curried2
}
}
return curried
}
var add1 = kkCurrying(add1);
var add2 = kkCurrying(add2);
var add3 = kkCurrying(add3);
console.log(add1(1));
console.log(add2(1, 2));
console.log(add3(1, 2, 3));
防抖节流
防抖
const input = document.querySelector("input")
let couter = 0;
const inputChange = function() {
console.log(`发送了第${++couter}次请求`);
}
input.oninput = debounce(inputChange, 2000)
function debounce(fn, delay) {
//1.定义一个定时器变量,来保存上次的定时器
let timer = null
// 2.真正执行的函数
const _debounce = function () {
// 3.如果定时器存在,取消上一次的定时器
if(timer) clearTimeout(timer)
timer = setTimeout(() => {
// 外部传入的的函数
fn()
},delay)
}
return _debounce
}
节流
const input = document.querySelector("input")
let couter = 0;
const inputChange = function() {
console.log(`发送了第${++couter}次请求`);
}
input.oninput = throttle(inputChange, 2000)
function throttle(fn, interval) {
let lastTime = 0
const _throttle = function() {
const nowTime = new Date().getTime();
const remainTime = interval - (nowTime - lastTime);
// 执行函数
if(remainTime <= 0) {
fn();
lastTime = nowTime
}
}
return _throttle
}