常用工具函数 (tools篇)

134 阅读1分钟

保留n位小数位数


export function formatNum (str, n = 2) {
    const bit = Math.pow(10, n)
    const f = Math.round(str * bit) / bit
    return f.toString()
}

保留小数

export const keepDecimal = (val, decimal = 2) => {
    if (typeof val === 'string' || val === undefined || val === null || Number.isNaN(val)) {
        return val
    }
    if (val % 1 === 0) {
        return val
    } else {
        return parseFloat(val.toFixed(decimal))
    }
}

js修改大小使用响应式

export function fontSize (res) {
    let clientWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
    let fontSize = (clientWidth / 20) / 750 * 20
    return res * fontSize
}

树形结构扁平化处理

export function treeIntoList (arr, key) {
    key = key || 'children'
    return [].concat(...arr.map(item => {
        let arr = item[key] ? treeIntoList(item[key], key) : []
        return [].concat(item, ...arr)
    }))
}

防抖

export function debounce(func, delay) {
    let timer
    return function (...args) {//我们调用一个函数,他会返回一个参数;我们拿到这个参数;
        if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {//定义延时函数;
        func.apply(this, args)//箭头函数中的this指向符集作用域;对象中有属性,方法,但并没有this
      }, delay)
    }
  }
  

节流

export function throttle(fn, delay) {
     let flag = true; 
     return () => { 
     if (!flag)  return flag = false;
     timer = setTimeout(() => {
    fn(); flag = true;
    }, delay);
   }
window.addEventListener( "scroll", 
  throttle(() => {
      console.log(111); 
}, 1000) );

数组中对象最大值

let list = [
{value:1000,name:'西红柿'},
{value:2000,name:'大西瓜'},
{value:3000,name:'小萝卜'},

]

let listMax = Math.max.apply(
            null,
            list.map(function(i) {
                return i.value;
            })