保留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)
}, 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;
})