function getRandomInt(min,max) {
return Math.floor(Math.random() * (max - min + 1) + min)
// return Math.floor(Math.random() * (max + 1))
}
// 洗牌函数(数组打乱)
function shuffle(arr) {
let _arr = arr.concat();
for (let i = 0; i < _arr.length; i++) {
let j = getRandomInt(0,i);
let t = _arr[i];
_arr[i] = _arr[j];
_arr[j] = t;
}
return _arr;
}
// 函数防抖(节流)
function debounce(func, delay, immediate = true) {
let timer;
return function (...args) {
if (timer) clearTimeout(timer);
// 默认立即执行方法,延后执行的话,会让人感觉有卡顿
if (immediate) {
// 定义现在是否能执行
let now = !timer;
if (now) func.apply(this, args);
// 不论timeout有没有值,都重新给timeout新添加一个定时器
// 等待wait时间后,将timeout设为null,代表可以继续执行次function
timer = setTimeout(() => {
timer = null;
}, delay);
} else {
// 如果不是立即执行此函数,则在等待 delay 延迟时间后执行方法
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
}
}
}
配合自定义指令使用
Vue.directive('debounce', {
bind(el, binding) {
let execFunc;
if (binding.value instanceof Array) {
// 函数传参
const [func, time = 500, immediate = true] = binding.value;
execFunc = Util.debounce(func, time, immediate);
} else {
// 函数不传参
execFunc = Util.debounce(binding.value, 500, true);
}
el.addEventListener('click', execFunc);
}
});
页面使用
<template>
<div>
<div class="btn" v-debounce="() => handleClick()">点击按钮</div>
</div>
</template>
<script>
export default {
name: "index",
methods: {
handleClick() {
console.log('handleClick')
}
}
}
</script>
<style scoped lang="scss">
.btn {
300px;
height: 80px;
line-height: 80px;
text-align: center;
color: white;
background-color: #30BC75;
}
</style>
// jsonp封装
import jsonp from 'jsonp'
// 转换url地址参数
const param = (param) => {
let url = ''
for (let key in param) {
let value = param[key] ? param[key] : '';
url += `&${key}=${encodeURIComponent(value)}`;
}
return url ? url.substring(1) : '';
}
// data是url地址的参数
export default (url,data,options) => {
url += (url.indexOf('?') < 0 ? '?' : '&') + param(data);
return new Promise((resolve, reject) => {
jsonp(url,options,(err,data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
// 确保函数只被调用一次
function once (fn) {
let called = false
return function () {
if (!called) {
called = true
fn.apply(this, arguments)
}
}
}
randomStr() {
return Math.random().toString(36).substr(2);
}
// 判断数据类型
// 在任何值上调用Object原生的toString方法,都会返回一个[object NativeConstructorName]格式的字符串
function isType(type) {
// return Object.prototype.toString.call() === `[object ${type}]`;
return function (args) {
return Object.prototype.toString.call(args) === `[object ${type}]`;
}
}
var isNumber = isType('Number');
console.log(isNumber('1')); // false
// 倒计时
function toTwo(value) {
return (value >= 10 ? '' : '0') + value;
}
// 此处可以传值(毫秒数),这里目前写死1分钟倒计时
function tocoundown(countdown) {
var time = 60;
var intervalId;
return function() {
intervalId = setInterval(() => {
if (time <= 0) {
clearInterval(intervalId);
} else {
setcountdowns(--time);
}
},1000);
}
}
function setcountdowns(time) {
let str = '';
if (time > 0) {
let minute = toTwo(Math.floor(time / 60 % 60)),
seconds = toTwo(Math.floor(time % 60));
str = `${minute}:${seconds}`;
} else {
str = '00:00';
}
console.log(str);
return str;
}
tocoundown()();
// 相对地址变成绝对地址
// 1、
var relative2absolute = function (url, base) {
if (!base) {
base = location.protocol + location.host;
}
return new URL(url, base).href;
}
// 2、
var relativetoabsolute = function (url, base) {
var ele = document.createElement('a');
ele.href = (base || '') + url;
return ele.href;
}
深拷贝
function deepClone(obj) {
let objClone = Array.isArray(obj) ? [] : {};
if (obj && typeof obj === 'object') {
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
if (obj[key] && typeof obj[key] === 'object') {
objClone[key] = deepClone(obj[key])
} else {
objClone[key] = obj[key]
}
}
}
}
return objClone
}
var obj = {
name: '张三',
meal: '男',
age: 20,
an: {
msg: 'hello'
}
}
var newObj = deepClone(obj);
newObj.name = '李四';
console.log(newObj); // {name: "李四", meal: "男", age: 20, an: {…}}
console.log(obj); // {name: "张三", meal: "男", age: 20, an: {…}}