let util = {};
// 对象扁平化处理
util.objectFlat = function (obj) {
let res = {};
let res2 = {};
Object.keys(obj).forEach((i) => {
if (obj[i] instanceof Object) {
res2 = objectFlat(obj[i]);
} else {
res[i] = obj[i];
}
});
return {
...res,
...res2,
};
};
// 防抖立即执行
util.debounceRightnow = function (fun, delay = 300) {
let timeout;
return function () {
let context = this;
let args = [...arguments];
if (!timeout) {
fun.apply(context, args);
} else {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
timeout = null;
}, delay);
};
};
// 截流函数
util.throttle = (func, wait, mustRun) => {
let timeout;
let startTime = new Date();
return function(...args) {
let context = this;
let curTime = new Date();
clearTimeout(timeout);
// 如果达到了规定的触发时间间隔,触发 handler
if (curTime - startTime >= mustRun) {
func.apply(context, args);
startTime = curTime;
// 没达到触发间隔,重新设定定时器
} else {
timeout = setTimeout(func, wait);
}
};
};
// 防抖函数
util.debounce = function (fn, ms = 300) {
let timer = null;
return function (...arg) {
timer && clearTimeout(timer);
timer = setTimeout(() => {
fn.call(this, ...arg);
}, ms);
};
};
// 数组以值为key及value转换为对象
util.array2object = (array) =>
array.reduce((obj, item) => {
obj[item] = item;
return obj;
}, {});
// 生成base74
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
var dataURL = canvas.toDataURL("image/png"); // 可选其他值 image/jpeg
return dataURL;
}
// 创建image实例 然后返回base64
image.createBase64Image = function (src, cb) {
var image = new Image();
image.src = src + "?v=" + Math.random(); // 处理缓存
image.crossOrigin = "*"; // 支持跨域图片
image.onload = function () {
var base64 = getBase64Image(image);
cb && cb(base64);
};
};
多维对象转一维对象
最新推荐文章于 2023-09-20 10:18:14 发布