日常js工具函数整理
数组对象中相同属性值的个数
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("音效失效");
}
}
模糊搜索
recursion(data, name) {
let result;
if (!data) {
return;
}
for (var i = 0; i < data.length; i++) {
let item = data[i];
if (item.name.toLowerCase().indexOf(name) > -1) {
result = item;
break;
} else if (item.children && item.children.length > 0) {
result = this.recursion(item.children, name);
if (result) {
return result;
}
}
}
return result;
},
onSearch(v) {
if (v) {
if (!this.recursion(this.subtable, v)) {
this.$message({
type: 'error',
message: '搜索不到',
});
} else {
this.tableData = [this.recursion(this.subtable, v)];
}
}
},
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 arr = [1,2,3];
const item = arr.splice(1, 1);
arr.splice(0,0,item);
console.log(arr);
不断更新…
欢迎关注我的公众号前端历劫之路
我创建了一个技术交流、文章分享群,群里有很多大厂的前端大佬,关注公众号后,点击下方菜单了解更多即可加我微信,期待你的加入。
作者:Vam的金豆之路
主要领域:前端开发
我的微信:maomin9761
微信公众号:前端历劫之路