10个有用的javascript代码片段

47 阅读1分钟

1. 获取URL参数

function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

使用方式:getURLParameter('参数名')

2. 数组去重

function uniqueArray(arr) {
    return Array.from(new Set(arr));
}

使用方式:uniqueArray(['a', 'b', 'c', 'a'])

3. 生成随机数

function getRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}

使用方式:getRandomNumber(1, 10)

4. 判断一个值是否为数字

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

使用方式:isNumber(123)

5. 防抖函数

function debounce(func, delay) {
    let timer;
    return function() {
        let context = this;
        let args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function() {
            func.apply(context, args);
        }, delay);
    }
}

使用方式:debounce(function() {console.log('hello')}, 1000)

6. 节流函数

function throttle(func, delay) {
    let last, timer;
    return function() {
        let context = this;
        let args = arguments;
        let now = +new Date();
        if (last && now < last + delay) {
            clearTimeout(timer);
            timer = setTimeout(function() {
                last = now;
                func.apply(context, args);
            }, delay);
        } else {
            last = now;
            func.apply(context, args);
        }
    }
}

使用方式:throttle(function() {console.log('hello')}, 1000)

7. 字符串转为驼峰命名

function toCamelCase(str) {
    return str.replace(/-([a-z])/g, function(match, p1) {
        return p1.toUpperCase();
    });
}

使用方式:toCamelCase('hello-world')

驼峰命名转为短横线连接

const hyphenateRE = /\B([A-Z])/g
export const hyphenate = (str) => {
  return str.replace(hyphenateRE, '-$1').toLowerCase()
}

hyphenate('helloWorld') // 'hello-world'

使用方式:hyphenate('helloWorld')

9. 数组扁平化

function flatten(arr) {
    return arr.reduce(function(prev, next) {
        return prev.concat(Array.isArray(next) ? flatten(next) : next);
    }, []);
}

使用方式:flatten([1, [2, 3], [4, [5, 6]]])

10. 获取当前时间

function getCurrentTime() {
    let date = new Date();
    let year = date.getFullYear();
    let month = ('0' + (date.getMonth() + 1)).slice(-2);
    let day = ('0' + date.getDate()).slice(-2);
    let hour = ('0' + date.getHours()).slice(-2);
    let minute = ('0' + date.getMinutes()).slice(-2);
    let second = ('0' + date.getSeconds()).slice(-2);
    return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
}

使用方式:getCurrentTime()