1. 数组去重
let a = [null,undefined,1,null,undefined,1,3,3,'1111','444','1111',true,false,false];
let b = [ ...new Set(a) ];
console.log(b); // [null, undefined, 1, 3, "1111", "444", true, false]
2. 字符串中变量的全局替换
let varItem = [
{
code: 'KHMC',
title: '客户名称'
},
{
code: 'CPMC',
title: '产品名称'
}
];
let msg = '我的${产品名称}是根据${客户名称}定义的${产品名称}';
varItem.forEach(i => {
let newReg = eval('\/\\$\\{'+i.title+'\\}\/');
msg = msg.replace(new RegExp(newReg,'g'),'${'+i.code+'}');
});
console.log(msg); // "我的${CPMC}是根据${KHMC}定义的${CPMC}"
3. 数组对象属性排序
let obj = [{age:1},{age:2},{age:10},{age:11},{age:5},{age:99},{age:7}];
function compare(property){
return function(a,b){
let value1 = a[property];
let value2 = b[property];
return value1 - value2;
}
}
let newObj = obj.sort(compare('age'));
console.log(newObj); // [{a:1},{a:2},{a:5},{a:7},{a:10},{a:11},{a:99}];