【项目实战】高频js代码简写、直接上干货

59 阅读2分钟

(一)数组对象的简写

1. 直接写入变量和函数,作为对象的属性和方法。

const fruit = 'apple';
const obj = {fruit};

// 等同于
const objCopy = { fruit: fruit } 

2. 键名可以用表达式/变量的形式使用

// 写法1
const obj = {['fru' + 'it']:'apple'}

// 写法2
const key = 'fruit'
const obj = {[key]:'apple'}

// 写法3
const obj = {
   fruit(){
       return 'apple'
   }
} // obj.fruit() 

// 等同于 
const objCopy = { fruit: fruit }

3. 对象的解构

const animal = { dog: '旺旺', cat: '猫', fish: '鱼' }
// 写法一
const dog = animal.dog
const cat = animal.cat
const fish = animal.fish
// 写法二
const { dog, cat, fish } = animal

console.log(dog, cat, fish) // 旺旺 猫 鱼

4. 拓展运算符

字符串中的拓展运算符

const str = { ...'hello world' }

str // {"0": "h","1": "e","2": "l","3": "l","4": "o","5": " ","6": "w","7": "o","8": "r","9": "l","10": "d"}

对象中的拓展运算符

const animal = { dog: '旺旺', cat: '猫', fish: '鱼' }
// 拷贝对象
const animalCopy = { ...animal}

console.log(animalCopy) // {"dog": "旺旺","cat": "猫","fish": "鱼"}
let obj1 = { a: { b: 1 } };
let { ...obj2 } = obj1;
obj1.a.b = 666;
obj2.a.b // 666

数组中的拓展运算符

// 数组的降维、合并
const arr = [...[1,2,3,4,5]] // [1,2,3,4,5]
// 或者
const arr = [1,2,3, ...[4,5]] // [1,2,3,4,5]
// 或者
const arr = [...[1,2,3], ...[4,5]] // [1,2,3,4,5]
// 数组对象的解构
const obj = { ...['dog', 'cat', 'fish'] }
obj // {"0": "dog","1": "cat","2": "fish"}

(二)javaScript常用的简写

1. 清楚所有的cookie

document.cookie.split(';').forEach(cookie => {
    const [name] = cookie.split('=');
    document.cookie = `${name}=; expires=${new Date(0).toUTCString()}; path=/`;
});

2. 移除重复项

const removeRepetition = (arr) => [...new Set(arr)];

3. 将http请求地址中的参数输出为键值对格式

const str = 'https://juejin.cn/post?a=1&b=2&c=3'
Object.fromEntries(str.split('?')[1].split('&').map(v => v.split('='))) // {a: '1', b: '2', c: '3'}

4. Set集合来进行数组去重、交集、并集和差集操作

  1. 数组去重:
const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // 输出 [1, 2, 3, 4, 5]
  1. 交集
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [4, 5, 6, 7, 8];
const intersection = arr1.filter(x => new Set(arr2).has(x));
console.log(intersection); // 输出 [4, 5]
  1. 并集
const arr1 = [1, 2, 3];
const arr2 = [3, 4, 5];
const union = [...new Set([...arr1, ...arr2])];
console.log(union); // 输出 [1, 2, 3, 4, 5]
  1. 差集
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [4, 5, 6, 7, 8];
const difference = arr1.filter(x => !new Set(arr2).has(x));
console.log(difference); // 输出 [1, 2, 3]

5. "?." 可选操作符

// 如果访问多层数据结构中未定义属性时通常代码直接报错,如果使用可选操作符可以避免代码本崩溃
const obj = {
    father: '张三',
    children:{
       name: '李四'
    }
}
// 通写
console.log(obj && obj.children && obj.children.age) // undefine
// 使用“?.”可选操作符简写
console.log(obj?.children?.age) // undefine

6. 将键值对的列表转为对象

const entriesArr = [["a", 1], ["b", 2], ["c", 3]];
Object.fromEntries(entriesArr); // { a: 1, b: 2, c: 3 }