本文总结开发过程中常用的js技巧,欢迎补充。
1. 数组去重
const arr = ['a', 'b', 'c', 'b', 'a'];
const newArr = [...new Set(arr)];
2. 对象数组去重(有重复键)
objectArrayDeduplication(arr, key){
const temp = new Map(); // 使用Map可以比对多种类型,不限于字符串
return arr.filter((item) => !temp.has(item[key]) && temp.set(item[key], true));
}
// 常用于过滤列表
const list = [{id: 1, name: 'a'}, {id: 1, name: 'a'}, {id: 2, name: 'b'}];
const newArr = objectArrayDeduplication(list, 'id'); // newArr: [{id: 1, name: 'a'}, {id: 2, name: 'b'}]
3. 对象数组取交集(相同键)
arrIntersectionByKey(arr1, arr2, key) {
const arr2Keys = arr2.map(item => item[key]);
return arr1.filter(item => arr2Keys.includes(item[key]));
}
const receivedCoupons = [{ name: 'a' },{ name: 'b' }];
const welfareCoupons = [{ name: 'a' }];
arrIntersectionByKey(receivedCoupons, welfareCoupons, 'name'); // [{ name: 'b' }]
4. 使用Map代替switch或多个if判断,该方式也是可避免代码复杂度过高的有效方法之一
function getStatusText(status) {
switch (status) {
case 1: return 'A';
case 2: return 'B';
case 3: return 'C';
default: return '';
}
}
// 使用Map替代
const statusMap = new Map()
.set(1, 'A')
.set(2, 'B')
.set(3, 'C');
const statusText = statusMap.get(status);