使用可选链(Optional Chaining)简化深层属性访问
在处理嵌套对象时,传统方式需要多层判断 && 来避免 Cannot read property 'xx' of undefined 错误,可选链 能让代码更简洁:

const user = { name: 'Alice', address: { city: 'Paris' } };
const city = user?.address?.city; // 'Paris',即使 address 不存在也不会报错
如果中间属性为 null 或 undefined,表达式会直接返回 undefined,避免程序崩溃。
空值合并运算符(Nullish Coalescing)处理默认值
当需要为变量设置默认值时, 会将假值(如 0、、false)也替换为默认值,而 仅在值为 null 或 undefined 时生效:
const config = { timeout: 0, retries: null };
const timeout = config.timeout ?? 3000; // 0(不会被替换)
const retries = config.retries ?? 3; // 3(null 被替换)
适合处理 API 返回的数值或布尔值场景。
使用解构赋值交换变量
无需临时变量即可交换两个变量的值:
let a = 1, b = 2; [a, b] = [b, a]; console.log(a, b); // 2, 1
同样适用于数组元素的交换或函数返回多值时的解构。
动态属性名计算对象字面量
通过 [expression] 语法动态生成对象属性名:
const dynamicKey = 'user_id';
const data = {
[dynamicKey]: 123,
['status_' + dynamicKey]: 'active'
};
// 结果:{ user_id: 123, status_user_id: 'active' }
适合根据变量或函数返回值构建对象结构。
数组扁平化(Flat)与去重(Set)
ES6 提供了 flat() 方法简化嵌套数组处理:
const nestedArr = [1, [2, 3], [4, [5]]]; const flatArr = nestedArr.flat(2); // [1, 2, 3, 4, 5](参数为深度)
结合 Set 去重:

const arr = [1, 2, 2, 3]; const uniqueArr = [...new Set(arr)]; // [1, 2, 3]
使用 Array.from 或展开运算符创建类数组对象
将类数组(如 arguments、NodeList)转为数组:
const args = Array.from(arguments);
const nodeList = [...document.querySelectorAll('div')];
也可用于生成指定长度的数组:
const range = Array.from({ length: 5 }, (_, i) => i + 1); // [1, 2, 3, 4, 5]
利用 Object.freeze 防止对象被修改
确保对象不可变(常用于配置项或常量):
const config = Object.freeze({ theme: 'dark' });
config.theme = 'light'; // 严格模式下会报错,静默模式下无效果
对于深层对象,需递归冻结或使用第三方库(如 deep-freeze)。
使用 调用可选方法链
在方法调用中避免因对象不存在而报错:
const user = { getName: () => 'Bob' };
const name = user?.getName?.(); // 'Bob',即使 user 为 undefined 也不会报错
特别适合处理异步加载或条件存在的对象。
字符串模板与标签模板
模板字符串支持多行和变量插值:
const name = 'Alice';
const greeting = `Hello, ${name}!
Welcome to JavaScript!`;
标签模板可自定义字符串处理逻辑:
const highlight = (strings, ...values) =>
strings.reduce((acc, str, i) => acc + str + (values[i] ? `<strong>${values[i]}</strong>` : ''), '');
const result = highlight`User: ${name}, Age: ${30}`;
// 输出: "User: <strong>Alice</strong>, Age: <strong>30</strong>"
使用 Promise.allSettled 处理多个 Promise
Promise.all 会在任一 Promise 拒绝时立即失败,而 allSettled 会等待所有 Promise 完成:

const promises = [Promise.resolve(1), Promise.reject('Error')];
Promise.allSettled(promises).then(results => {
results.forEach(result => {
console.log(result.status, result.reason || result.value);
});
// 输出: "fulfilled" 1, "rejected" "Error"
});
适合需要统一处理成功或失败结果的场景。
利用 Intl API 格式化日期和数字
原生国际化 API 可简化格式化操作:
const date = new Date();
const formattedDate = new Intl.DateTimeFormat('zh-CN', {
year: 'numeric', month: '2-digit', day: '2-digit'
}).format(date); // "2023/10/01"
const number = 1234567.89;
const formattedNum = new Intl.NumberFormat('en-US', {
style: 'currency', currency: 'USD'
}).format(number); // "$1,234,567.89"
支持多种语言和地区规则。
使用 WeakMap 和 WeakSet 管理内存
WeakMap 的键必须是对象,且不会阻止垃圾回收,适合存储临时关联数据:
const cache = new WeakMap();
function processData(obj) {
if (!cache.has(obj)) {
const result = /* 复杂计算 */;
cache.set(obj, result);
}
return cache.get(obj);
}
当 obj 不再被引用时,cache 中的对应条目会被自动清除,避免内存泄漏。
这些技巧涵盖了从基础语法到高级特性的多个方面,合理运用可以显著提升代码的可读性、健壮性和开发效率,在实际项目中,建议根据场景选择合适的方法,避免过度使用导致代码复杂化。



















