防抖方法

/**
* 防抖
* @param {Function} func 要执行的回调函数
* @param {Number} wait 延时的时间
* @param {Boolean} immediate 是否立即执行
* @return null
*/
let timeout;
export default function Debounce(func, wait = 3000, immediate = true) {
// 清除定时器
if (timeout !== null) clearTimeout(timeout);
// 立即执行,此类情况一般用不到
if (immediate) {
var callNow = !timeout;
timeout = setTimeout(function() {
timeout = null;
}, wait);
if (callNow) typeof func === 'function' && func();
} else {
// 设置定时器,当最后一次操作后,timeout不会再被清除,所以在延时wait毫秒后执行func回调方法
timeout = setTimeout(function() {
typeof func === 'function' && func();
}, wait);
}
}
Debounce(()=>{
console.log(1);
});

函数只执行一次

function once (fn){
let called = false
return function () {
if (!called) {
called = true
fn.apply(this, arguments)
}
}
}
function func (){
console.log(1);
}

//调用闭包函数
let onlyOnce = once(func);

onlyOnce(); // 1
onlyOnce();

构造函数回调方法

function Watcher(cb){
this.cb = cb;
}
Watcher.prototype.get=function(data){
this.cb(data);
}
new Watcher((v)=>{
console.log(v);
}).get('admin');

用 apply 将数组各项添加到另一个数组

var array = ['a', 'b'];
var elements = [0, 1, 2];
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]

微信JS-SDK 调用

import wx from 'weixin-js-sdk' //引入微信js-sdk
import { getWXSignature } from '../request/api'
const custom = function(url, jsApiList) {
return getWXConfig(url, jsApiList)
}
function getWXConfig(url, jsApiList) {
getWXSignature({ url })
.then(res => {
let { appId, timestamp, noncestr, signature } = res.data
console.log(appId, timestamp, noncestr, signature, jsApiList, url)
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: appId, // 必填,公众号的唯一标识
timestamp: timestamp, // 必填,生成签名的时间戳
nonceStr: noncestr, // 必填,生成签名的随机串
signature: signature, // 必填,签名
jsApiList: jsApiList, // 必填,需要使用的JS接口列表
})
wx.error(function(res) {
console.log('wxerr', res)
})
})
.catch(err => {
console.log(err)
})
}
export default custom

// ***
getWeiXinConfig() {
let url = window.location.href
// let url = encodeURIComponent(location.href.split('#')[0])
this.$getWXConfig(url, ['scanQRCode'])
}
//微信扫一扫
wxSweep() {
wx.scanQRCode({
needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
scanType: ['barCode'], //'qrCode', 可以指定扫二维码还是一维码,默认二者都有
success: function(res) {
var result = res.resultStr // 当needResult 为 1 时,扫码返回的结果
console.log(result)
if (this.type === 1) {
//位置上传
this.$router.push({
path: '/updateLocation',
query: {
projectId: this.projectId,
type: 1,
mac: result,
},
})
} else if (this.type === 2) {
//模块更换
this.$router.push({
path: '/changeModule',
query: {
projectId: this.projectId,
type: 1,
mac: result,
},
})
} else {
//开关更换
this.$router.push({
path: '/changeSwitch',
query: {
projectId: this.projectId,
type: 1,
mac: result,
},
})
}
},
})
},

js 递归数组降维

let children = [1, [2, 3], [4, [5, 6, [7, 8]]], [9, 10]];
function simpleNormalizeChildren(children) {
for (let i = 0; i < children.length; i++) {
if (Array.isArray(children[i])) {
children = Array.prototype.concat.apply([], children);
simpleNormalizeChildren(children)
}
}
return children;
}
console.log(simpleNormalizeChildren(children));
simpleNormalizeChildren(children); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

js 数组降维(二维降一维)

function simpleNormalizeChildren(children) {
for (let i = 0; i < children.length; i++) {
if (Array.isArray(children[i])) {
return Array.prototype.concat.apply([], children)
}
}
return children
}
let arrs = [
[
'1'
],
[
'3'
]
];
const arr = simpleNormalizeChildren(arrs);
console.log(arr); // ['1','3']

File对象 转 base64

inputImage(e) {
let img = e.target.files[0];
if (img) {
this.blobToDataURL(img);
}
},
blobToDataURL(blob) {
let reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = function(evt) {
let base64 = evt.target.result;
console.log(base64);
};
},

Vue3

const oDiv = document.createElement('div');
const oScript = document.createElement('script');
oDiv.setAttribute('id', 'app');
oScript.type = 'text/javascript';
oScript.src = "https://unpkg.com/vue@next";
document.body.appendChild(oDiv);
document.body.appendChild(oScript);


window.onload = function () {
const { createApp,ref } = Vue;
const App = {
template: `
<div>{{msg}}</div>
<p>{{count}}</p>
`,
data(){
return {
msg:'maomin'
}
},
setup(){
let count = ref(0);

return {
count
}
}
}
createApp(App).mount('#app');
}

递归寻找操作(已删除指定项为例)

// 递归寻找
recursion(data, id) {
let result;
if (!data) {
return;
}
for (let i = 0; i < data.length; i++) {
let item = data[i];
if (item.breakerId === id) {
result = item;
data.splice(i, 1);
break;
} else if (item.childrenBranch && item.childrenBranch.length > 0) {
result = this.recursion(item.childrenBranch, id);
if (result) {
return result;
}
}
}

return result;
},

递归数组,将数组为空设为undefined

function useTree(data) {
for (let index = 0; index < data.length; index++) {
const element = data[index];
if (element.childrenBranch.length < 1) {
element.childrenBranch = undefined;
} else {
useTree(element.childrenBranch);
}
}
return data;
}

数组对象中相同属性值的个数

group(arr) {
var obj = {};
if (Array.isArray(arr)) {
for (var i = 0; i < arr.length; ++i) {
var isNew = arr[i].isNew;
if (isNew in obj) obj[isNew].push(arr[i]);
else obj[isNew] = [arr[i]];
}
}
return obj;
},
max(obj) {
var ret = 0;
if (obj && typeof obj === "object") {
for (var key in obj) {
var length = obj[key].length;
if (length > ret) ret = length;
}
}
return ret;
},
var data = [
{
addr: "1",
isNew: false,
},
{
addr: "2",
isNew: false,
}
]
max(group(data) // 2

检测版本是vue3

import { h } from 'vue';
const isVue3 = typeof h === 'function';
console.log(isVue3)

检测数据对象中是否有空对象

let arr = [{},{name:'1'}]
const arr = this.bannerList.filter(item =>
item == null || item == '' || JSON.stringify(item) == '{}'
);
console.log(arr.length > 0 ? '不通过' : '通过')

深拷贝

/* @param {*} obj
* @param {Array<Object>} cache
* @return {*}
*/
function deepCopy (obj, cache = []) {
// just return if obj is immutable value
if (obj === null || typeof obj !== 'object') {
return obj
}

// if obj is hit, it is in circular structure
const hit = find(cache, c => c.original === obj)
if (hit) {
return hit.copy
}

const copy = Array.isArray(obj) ? [] : {}
// put the copy into cache at first
// because we want to refer it in recursive deepCopy
cache.push({
original: obj,
copy
})

Object.keys(obj).forEach(key => {
copy[key] = deepCopy(obj[key], cache)
})

return copy
}

const objs = {
name:'maomin',
age:'17'
}

console.log(deepCopy(objs));

h5文字转语音

speech(txt){
var synth = null;
var msg = null;
synth = window.speechSynthesis;
msg = new SpeechSynthesisUtterance();
msg.text = txt;
msg.lang = "zh-CN";
synth.speak(msg);
if(window.speechSynthesis.speaking){
console.log("音效有效");
} else {
console.log("音效失效");
}
}

模糊搜索

getObjByName(list, name) {
//判断list是否是数组
if (!(list instanceof Array)) {
return null;
}

//遍历数组
for (let i in list) {
let item = list[i];
if (item.name === name) {
return item;
} else {
//查不到继续遍历
if (item.children) {
let value = this.getObjByName(item.children, name);
//查询到直接返回
if (value) {
return value;
}
}
}
}
}

input 数字类型

<el-input
v-model.number="form.redVal"
type="number"
@keydown.native="channelInputLimit"
placeholder="请输入阈值设定"
maxlength="8"
></el-input>

channelInputLimit(e) {
let key = e.key;
// 不允许输入‘e‘和‘.‘
if (key === 'e' || key === '.') {
e.returnValue = false;
return false;
}
return true;
},

排序(交换位置)

const list = [1,2,3,4,5,6];
function useChangeSort (arr,oldIndex,newIndex){
const targetRow = arr.splice(oldIndex, 1)[0];
const targetRow1 = arr.splice(newIndex, 1)[0];
arr.splice(newIndex, 0, targetRow);
arr.splice(oldIndex, 0, targetRow1);
return arr
}
console.log(useChangeSort(list,5,0)); // [6, 2, 3, 4, 5, 1]

格式化时间

/**
* Parse the time to string
* @param {(Object|string|number)} time
* @param {string} cFormat
* @returns {string | null}
*/
export function parseTime(time, cFormat) {
if (arguments.length === 0 || !time) {
return null;
}
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
let date;
if (typeof time === 'object') {
date = time;
} else {
if (typeof time === 'string') {
if (/^[0-9]+$/.test(time)) {
// support "1548221490638"
time = parseInt(time);
} else {
// support safari
// https://stackoverflow.com/questions/4310953/invalid-date-in-safari
time = time.replace(new RegExp(/-/gm), '/');
}
}

if (typeof time === 'number' && time.toString().length === 10) {
time = time * 1000;
}
date = new Date(time);
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
};
const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
const value = formatObj[key];
// Note: getDay() returns 0 on Sunday
if (key === 'a') {
return ['日', '一', '二', '三', '四', '五', '六'][value];
}
return value.toString().padStart(2, '0');
});
return time_str;
}


不断更新…




  • 欢迎关注我的公众号​​前端历劫之路​
  • 我创建了一个技术交流、文章分享群,群里有很多大厂的前端大佬