Hi FE !
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
  • js 优化小技巧

js 优化小技巧

if (x == "yk" || x == "qdleader" || x == "dbj") {
}
优化为;
if (["yk", "qdleader", "dbj"].includes(x)) {
}
let test;
if (x > 100) {
  test = true;
} else {
  test = false;
}

优化为;
let test = x > 100;
  1. Null, Undefined, 空值检查
// 冗余
if (first !== null || first !== undefined || first !== "") {
  let second = first;
}

// 简洁
let second = first || "";

函数条件调用

// 冗余
function test1() {
  console.log("test1");
}
function test2() {
  console.log("test2");
}
var test3 = 1;
if (test3 == 1) {
  test1();
} else {
  test2();
}

// 简单
(test3 === 1 ? test1 : test2)();
switch (data) {
  case 1:
    test1();
    break;

  case 2:
    test2();
    break;

  case 3:
    test3();
    break;
}

// 简洁
let data = {
  1: test1,
  2: test2,
  3: test3,
};

data[anything] && data[anything]();
  1. 幂乘
Math.pow(2, 3);

较简单写法;
2 ** 3; // 8
  1. 重复字符串多次
// 冗余
let test = "";
for (let i = 0; i < 5; i++) {
  test += "qdleader ";
}

// 简洁
"qdleader ".repeat(5);

清理数组

const arr = [0, 1, false, 2, "", 3];
const cleanedArray = arr.filter(Boolean); // Result: cleanedArray = [1, 2, 3]
Edit this page
最近更新: 2025/6/27 02:24
Contributors: qdleader
qdleader
本站总访问量 129823次 | 本站访客数 12人