js代码优化技巧

Posted by sqq5682 on January 1, 2025

变量名称重复问题

import { var1, obj } from './module1.js'; // import变量和下面声明变量重复
const { var1 } = obj // 解构对象出现也会出现变量重复
let var1 = [1,2,3]

改进

import { var1 as var1FromImport, obj } from './module1.js';
const { var1: var1FromObj } = obj
let var1 = [1,2,3]

带有多个条件的 if 语句

// Longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
    //logic
}

改进

//shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
   //logic
}

简化 if true…else

// Longhand
let test: boolean;
if (x > 100) {
    test = true;
} else {
    test = false;
}

改进

// Shorthand
let test = (x > 10) ? true : false;
//或者我们也可以直接用
let test = x > 10;
console.log(test);

如果有嵌套的条件,可以这么做。

let x = 300,
test2 = (x > 100) ? 'greater than 100' : (x < 50) ? 'less 50' : 'between 50 and 100';
console.log(test2); // "greater than 100"

null、undefined的检查

// Longhand
if (test1 !== null || test1 !== undefined) {
    let test2 = test1;
}

改进

// Shorthand
let test2 = test1 || '默认值'; // || test1为任何假值(如0、false、空字符串等)时就返回
let test3 = test1 ?? '默认值'; // ?? 空值合并操作符 test1严格等于null或undefined
let test3 = test1 && '默认值'; 

?可选链操作符

const name = obj && obj.name;

改进

const name = obj?.name ?? '默认值';

给多个变量赋值

//Longhand 
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;

改进

//Shorthand 
let [test1, test2, test3] = [1, 2, 3];

添加对象属性

const hasCar = true
const people = {
  name: '张三',
  age: 18
}
if(hasCar){
  people.hasCar = true
}

改进

const hasCar = true
const hasCarObj = hasCar ? {
  hasCar: true
} : {}
const people = {
  name: '张三',
  age: 18,
  ...hasCarObj
}

使用reduce替代filter().map()

const arr = [1, 2, 3, 4, 5];
const filteredArr = arr.filter(item => item % 2 === 0).map(item => item * 2);
// filteredArr : [4, 8]

改进

const arr = [1, 2, 3, 4, 5];

const reducedArr = arr.reduce((acc, item) => {
  if (item % 2 === 0) {
    acc.push(item * 2);
  }
  return acc;
}, []);
// reducedArr: [4, 8]