JS 高效编程必备:这些魔法运算符让代码更简洁
一、可选链运算符:深层属性访问的安全卫士
const student = {
score: {
math: 98
}
};
if (student && student.score) {
console.log(student.score.math);
}
1.1 语法与核心特性
console.log(student?.score?.math); // 98const Student = ({ getScore }: { getScore?: () => void }) => {
useEffect(() => {
getScore?.(); // 自动跳过undefined的情况
}, []);
return <div></div>;
};
1.2 数组与函数的组合应用
const arr = [10, 20];
console.log(arr?.[1]); // 20
// 复杂结构中的组合使用
const student = {
score: {
math: [
98,
67,
() => {
return 99;
}
]
}
};
console.log(student?.score?.math?.[2]?.()); // 99
1.3 注意事项:不可用于赋值
arr?.[1] = 2; // 抛出SyntaxError
document.querySelector('.score')?.innerhtml = '98'; // 语法错误二、空值合并运算符:精准处理默认值
const getScore = (score: number) => {
return score || 1; // 当score为0时返回1,这不符合业务逻辑
};
console.log(getScore(0)); // 1
2.1 与逻辑或的本质区别
const getScore = (score: number) => {
return score ?? 1; // 仅当score为null/undefined时返回1
};
console.log(getScore(0)); // 0
console.log(getScore(undefined)); // 1
2.2 链式赋值语法
let userScore;
userScore ??= 100; // 等同于 userScore = userScore ?? 100
console.log(userScore); // 100三、逻辑赋值运算符:语法糖的进阶应用
// 传统写法
score = score || 1;
age = age && 24;
// 新写法
score ||= 1; // 等价于 score = score || 1
age &&= 24; // 等价于 age = age && 24let config = {};
config.apiUrl ||= 'https://api.example.com';
config.timeout &&= 5000;四、幂运算符:数学计算的便捷写法
console.log(2 ** 10); // 1024,等价于Math.pow(2, 10)
console.log(3 ** 3); // 27
// 支持负数指数
console.log(4 ** -2); // 0.0625,等价于1/(4*4)五、实战建议与兼容性处理
5.1 开发效率提升点
- 在处理 API 返回的深层数据结构时,优先使用可选链运算符
- 配置项默认值设置时,根据业务场景选择??或||
- 函数参数默认值建议使用||=语法糖
- 数学计算中多用**替代 Math.pow ()
5.2 兼容性解决方案
- 安装必要插件:
npm install @babel/plugin-proposal-optional-chaining @babel/plugin-proposal-nullish-coalescing-operator- 在.babelrc 中配置:
{
"plugins": ["@babel/plugin-proposal-optional-chaining", "@babel/plugin-proposal-nullish-coalescing-operator"]
}结语
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!