每个开发人员必须知道的 15 个 JavaScript 技巧

1. 一步解构并重命名

在对象解构期间重命名变量以避免命名冲突:

const user = { name: 'Rutvik', age: 22 };
const { name: userName, age: userAge } = user;
console.log(userName); // Rutvik
console.log(userAge);  // 22

2. 带有函数调用的可选链

调用函数之前确保它存在:

const user = {
  getName: () => 'Rutvik',
};
console.log(user.getName?.());   // Rutvik
console.log(user.getAge?.());    // undefined

3. 使用 ||= 运算符进行默认赋值

仅当变量为空、未定义或 falsey 时才分配默认值:

let count;
count ||= 10;
console.log(count); // 10

4. 使用扩展运算符将 NodeList 转换为数组

快速将 NodeList 转换为数组:

const divs = document.querySelectorAll('div');
const divArray = [...divs];
console.log(Array.isArray(divArray)); // true

5. 使用默认值解构数组/对象

通过在解构过程中分配默认值来避免未定义:

const user = { name: 'Rutvik' };
const { name, age = 22 } = user;
console.log(age); // 22

6. 从数组中删除假值

过滤掉 0、null 或 undefined 等虚假值:

const arr = [0, 'hello', null, 42, false, 'world'];
const filtered = arr.filter(Boolean);
console.log(filtered); // ["hello", 42, "world"]

7. 根据属性对对象数组进行排序

根据特定属性对对象进行排序:

const users = [{ name: 'Rohit', age: 38 }, { name: 'Virat', age: 36 }];
users.sort((a, b) => a.age - b.age);
console.log(users); // [{ name: 'Virat', age: 36 }, { name: 'Rohit', age: 38 }]

8. 对象解构的默认参数

解构并设置函数参数的默认值:

function createUser({ name = 'Rutvik', age = 22 } = {}) {
  console.log(name, age);
}
createUser();               // Rutvik 22
createUser({ name: 'Rohit' }); // Rohit 22

9. 使用 Object.assign() 进行浅复制

浅复制对象而不影响原始对象:

const original = { a: 1, b: 2 };
const copy = Object.assign({}, original);
copy.a = 3;
console.log(original.a); // 1 (unchanged)

10. 使用 Array.flat(Infinity) 展平嵌套数组

轻松展平深度嵌套的数组:

const nested = [1, [2, [3, [4]]]];
console.log(nested.flat(Infinity)); // [1, 2, 3, 4]

11. 使用 ! 切换布尔值

切换布尔值:

let isVisible = false;
isVisible = !isVisible;
console.log(isVisible); // true

12. 使用 concat() 合并多个数组

一步合并数组:

const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = [5, 6];
const merged = arr1.concat(arr2, arr3);
console.log(merged); // [1, 2, 3, 4, 5, 6]

13. 快速获取数组中的最后一项

检索数组中的最后一项:

const arr = [1, 2, 3, 4];
console.log(arr.at(-1)); // 4

14. 使用 Math.round() 和模板字面量对数字进行四舍五入

轻松格式化四舍五入的数字:

const num = 3.14159;
console.log(`${Math.round(num * 100) / 100}`); // 3.14

15. 使用 Array.from() 将类数组对象转换为数组

将类数组对象转换为数组:

function example() {
  const argsArray = Array.from(arguments);
  console.log(argsArray);
}
example(1, 2, 3); // [1, 2, 3]

祝你编码愉快!🚀