1. 模板字符串替代字符串拼接
// 传统方式
const greeting = 'Hello, ' + user.name + '! You have ' + user.notifications + ' notifications.';
// 模板字符串
const greeting = `Hello, ${user.name}! You have ${user.notifications} notifications.`;
模板字符串不仅代码更简洁,而且可读性更强,尤其是在处理多行文本时。
2. 解构赋值提取字符串
// 传统方式
const firstChar = str.charAt(0);
const lastChar = str.charAt(str.length - 1);
// 解构赋值
const [firstChar, ...rest] = str;
const lastChar = str.slice(-1);
解构赋值不仅可以用于数组,还可以用于字符串,使得字符提取变得更加简洁。
3. 使用String.prototype.includes代替indexOf
// 传统方式
if
订阅专栏 解锁全文

472

被折叠的 条评论
为什么被折叠?



