代码题

43 阅读1分钟

扁平化数据

const arr = [1, [2, [3, [4, 5]]], 6];
//1,flat
// 默认深度为 1
const flatArr1 = arr.flat();
console.log(flatArr1); // 输出: [1, 2, [3, [4, 5]], 6]

// 指定深度为 2
const flatArr2 = arr.flat(2);
console.log(flatArr2); // 输出: [1, 2, 3, [4, 5], 6]

// 指定深度为 Infinity,完全扁平化
const flatArrInfinity = arr.flat(Infinity);
console.log(flatArrInfinity); // 输出: [1, 2, 3, 4, 5, 6]

节流

节流是指,当事件被连续触发时,在设定的一段时间内,只执行一次该事件的回调函数

    function throttle(func, wait) {
        let lastTime = 0;
        return function(...args) {
            const now = new Date().getTime();
            if (now - lastTime >= wait) {
                lastTime = now;
                func.apply(this, args);
            }
        };
    };
    // 示例函数
    function exampleFunction() {
        console.log('Function', new Date().toLocaleTimeString());
    };
    // 使用节流函数
    const throttledFunction = throttle(exampleFunction, 2000);
    // 模拟频繁调用
    setInterval(throttledFunction, 500);

防抖

当事件被连续触发时,只有在最后一次触发事件后的延迟时间内没有再次触发,才会执行目标函数;

// 防抖函数
    function debounce(fn, time) {
        let timeout;
        return function (...args) {
            if (timeout) {
                clearTimeout(timeout);
            }
            timeout = setTimeout(() => {
                fn.apply(this, args);
            }, time);
        };
    }
    // 示例函数
    function exampleFunction(value) {
        console.log('Function', 'value' + value, new Date().toLocaleTimeString());
    }
    // 使用防抖函数
    const debouncedFunction = debounce(exampleFunction, 2000);
    // 模拟频繁调用
    setTimeout(() => {
        debouncedFunction('test')
    }, 500);