1、可选链
const email = user?.email ?? "N/A"; // 等价于 (user&&user.email)|| "N/A"
const street = user?.billing?.address?.street ?? "N/A";
const street = user?.billing?.address?.state ?? "N/A";注:调用方法 ?.() 调用动态变量 ?.[staName]
2、async 与 awit 的使用 (避免回调过多)
async function sendUserStatistics() {
try {
const user = await getUser();
const profile = await getProfile(user);
const account = await getAccount(profile);
const reports = await getReports(account);
return sendStatistics(reports);
} catch (e) {
console.error(err);
}
}3、错误处理 (处理抛出的错误和 reject 的 promise)
try {
// Possible erronous code
} catch (e) {
// Follow the most applicable (or all):
// 1- More suitable than console.log
console.error(e);
// 2- Notify user if applicable
alertUserOfError(e);
// 3- Report to server
reportErrorToServer(e);
// 4- Use a custom error handler
throw new CustomError(e);
}4、使用版本控制 (无需保留历史版本,git log 可以查到)
5、驼峰式命名变量,减少注释
js 干净简洁写法
猜你喜欢
转载自blog.csdn.net/qq_42181155/article/details/121624806
今日推荐
周排行