JavaScript 实用技巧

分享一些日常开发中常用的 JavaScript 技巧和最佳实践。

1. 可选链操作符

可选链操作符 ?. 可以安全地访问深层嵌套的属性:

const city = user?.address?.city;

2. 空值合并操作符

空值合并操作符 ?? 在值为 null 或 undefined 时提供默认值:

const name = user.name ?? 'Anonymous';

3. 结构赋值

简化从对象和数组中提取值的过程:

const { name, age } = user;
const [first, ...rest] = items;

4. Promise.allSettled

等待所有 Promise 完成,无论成功或失败:

const results = await Promise.allSettled([
  fetch('/api/users'),
  fetch('/api/posts'),
]);

results.forEach(result => {
  if (result.status === 'fulfilled') {
    console.log(result.value);
  } else {
    console.error(result.reason);
  }
});

5. Array.prototype.at()

使用负索引访问数组元素:

const last = arr.at(-1);  // 等同于 arr[arr.length - 1]

6. 结构赋值重命名

const { name: userName, age: userAge } = user;

7. Object.hasOwn()

替代 hasOwnProperty 的更可靠方法:

if (Object.hasOwn(obj, 'key')) {
  // ...
}
保持好奇,持续学习。

以上这些技巧在日常开发中非常实用。JavaScript 不断演进,关注新特性可以让我们写出更简洁、更安全的代码。

← 返回首页