export function genID() {
let d = new Date().getTime();
let appid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(
c
) {
let r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == "x" ? r : (r & 0x3) | 0x8).toString(16);
});
return appid;
}
处理金额小数点后保留几位
export function formatNumber(value, num) {
if (value === "" || value === null) return "";
let a, b, c, i;
a = value.toString();
b = a.indexOf(".");
c = a.length;
if (num === 0) {
if (b !== -1) {
a = a.substring(0, b);
}
} else {
//如果没有小数点
if (b === -1) {
a = a + ".";
for (i = 1; i <= num; i++) {
a = a + "0";
}
} else {
//有小数点,超出位数自动截取,否则补0
a = a.substring(0, b + num + 1);
for (i = c; i <= b + num; i++) {
a = a + "0";
}
}
}
return a;
}
缓存
// 设置缓存项
export function setSessionItem(moduleName, key, value) {
let val = getSessionItem(moduleName) || {};
val[key] = value;
localStorage.setItem(moduleName, JSON.stringify(val));
}
// 读取缓存项
export function getSessionItem(moduleName, key) {
if (key) {
return (
localStorage.getItem(moduleName) &&
JSON.parse(localStorage.getItem(moduleName))[key]
);
} else {
return JSON.parse(localStorage.getItem(moduleName));
}
}
// 删除缓存项
export function removeSessionItem(moduleName, key) {
if (key) {
let val = getSessionItem(moduleName);
delete val[key];
localStorage.setItem(moduleName, JSON.stringify(val));
} else {
localStorage.removeItem(moduleName);
}
}
非立即执行版 (非立即执行版的意思是触发事件后函数不会立即执行,而是在 n 秒后执行,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。)
function debounce(func, wait) {
let timeout;
return function () {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context, args)
}, wait);
}
}
立即执行版(立即执行版的意思是触发事件后函数会立即执行,然后 n 秒内不触发事件才能继续执行函数的效果)
function debounce(func,wait) {
let timeout;
return function () {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout);
let callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, wait)
if (callNow) func.apply(context, args)
}
}
函数节流 (使得一定时间内只触发一次函数。原理是通过判断是否到达一定时间来触发函数。)
时间戳版
function throttle(func, wait) {
let previous = 0;
return function() {
let now = Date.now();
let context = this;
let args = arguments;
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
}
}
定时器版
function throttle(func, wait) {
let timeout;
return function() {
let context = this;
let args = arguments;
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args)
}, wait)
}
}
}