js工具

作者: 进击的蒸汽机 | 来源:发表于2018-03-22 17:28 被阅读0次
      /**
     * [多维数组解一维]
     * @param  {Array } array [待处理数组]
     * @param  {Number} depth [解构深度]
     * @return {Array }       [返回新数组]
     */
    function flattenDepth(array, depth = 1) {
        // 创建一个新数组
        let result = [];
        array.forEach( item => {
            if(Array.isArray(item) && depth > 0) {
                // 递归解构
                result.push(...(flattenDepth(item, --depth)))
            } else {
                result.push(item)
            }
        } )
    
        return result;
    };
    
    /**
     * [cloneValue 对象拷贝]
     * @param  {[type]}  value  [待处理对象]
     * @param  {Boolean} isDeep [深浅拷贝]
     * @return {[type]}         [结果]
     */
    function cloneValue(value, isDeep) {
        if(value === null) return null;
        if(typeof value !== 'object') return value;
        if(Array.isArray(value)) {
            if(isDeep) {
                return value.map( item => cloneValue(item, true) )
            }
            return [].concat(value);
        } else {
            if(isDeep) {
                let obj = {};
                Object.keys(value).forEach( item => {
                    obj[item] = cloneValue(value[item], true)
                } );
                return obj;
            }
            return { ...value }
        }
    
    }
    
    function debounce(fun, wait) {
        let timer;
        return function () {
            let context = this;
            let args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function() {
                fun.apply(context, args);
            }, wait);
        }
    }
    
    

    相关文章

      网友评论

          本文标题:js工具

          本文链接:https://www.haomeiwen.com/subject/irtzqftx.html