大家好,我是 前端架构师 - 大卫。
更多优质内容请关注微信公众号 @前端大卫。
初心为助前端人🚀,进阶路上共星辰✨,
您的点赞👍与关注❤️,是我笔耕不辍的灯💡。
背景
本篇文章整理了一些常见的 JavaScript 语法优化技巧,并标注了每个特性的 ECMAScript 版本,以帮助开发者更好地理解和应用这些特性。
1. 多次解构拿到最终属性值
ES6 (2015) 引入了解构赋值。
js
const obj = {
part: {
name: "David",
age: 37
}
};
const {
part,
part: { name, age }
} = obj;
console.log(part); // { name: "David", age: 37 }
console.log(name, age); // David 37
2. 模版字符串当作函数参数
ES6 (2015) 引入了模板字符串(Template literals
)
ts
function getPersonInfo(template: TemplateStringsArray, person: string, age: number) {
console.log(template); // ["", " is ", " years old"]
console.log(person); // Lydia
console.log(age); // 21
}
const person = "Lydia";
const age = 21;
getPersonInfo`${person} is ${age} years old`;
3. 解构字符串
ES6 (2015) 引入了扩展运算符(Spread operator
)
js
[...'Lydia']; // ["L", "y", "d", "i", "a"]
4. 生成随机字符串
- ES6 (2015) 引入
toString(36)
进制转换 - ES8 (2017) 引入
padEnd
代码解析:
- Math.random() 生成随机数
0.6142088877102427
- toString(36) 转换成36进制
0.m40j2pdqw8o
- substr(2, 2+8) 进行字符串截取。
- padEnd 末尾补 0
js
const generatorRandomString = (length) => {
return Math.random()
.toString(36)
.slice(2, 2 + length)
.padEnd(length, "0");
};
generatorRandomString(8); // 'm40j2pdq'
5. 数字分隔符
ES12 (2021) 引入数字分隔符
js
const myMoney = 1_000_000_000_000;
// 等价于
const myMoney = 1000000000000;
6. while 简写循环
js
let i = 0;
while (i < 3) {
i++;
console.log(i);
}
// 简写
let i = 0;
while (i++ < 3) {
console.log(i);
}
7. Array.includes
判断多个 if 条件
ES7 (2016) 引入 includes
js
if (x === "abc" || x === "def" || x === "ghi") {
// logic
}
// 简写
if (["abc", "def", "ghi"].includes(x)) {
// logic
}
8. 字符串转数字
js
parseInt("32");
// 简写
"32" * 1;
+"32";
9. 数组去重
ES6 (2015) 引入 Set
js
const uniqueArray = (arr) => [...new Set(arr)];
10. 快速幂运算
ES7 (2016) 引入 **
运算符
js
Math.pow(2, 3); // 8
// 简写
2 ** 3;
11. 交换变量值
ES6 (2015) 引入解构赋值
js
let a = 1, b = 2;
let temp = a;
a = b;
b = temp;
// 简写
let a = 1, b = 2;
[a, b] = [b, a];
12. 判断一个元素是否能在数组里找到
ES7 (2016) 引入 includes
js
const arr = [0, 1];
arr.includes(0); // true
错误写法如下, 因为 0
在 js 里是 false
。
js
const arr = [0, 1];
const foundNumber = arr.find(item=>item===0);
if(foundNumber){
console.log('找到了');
}
注: JS 里的假值还有
undefined, null, NaN, 0, '', false
13. 三元运算符简化条件判断
js
let result;
if(condition){
result = 'yes';
}else{
result = 'no';
}
// 简写
const result = condition ? 'yes' : 'no';
14. switch 语句优化成用字典的形式
js
function getDayName(day) {
switch (day) {
case 1: return "Monday";
case 2: return "Tuesday";
case 3: return "Wednesday";
case 4: return "Thursday";
case 5: return "Friday";
case 6: return "Saturday";
case 7: return "Sunday";
default: return "Invalid day";
}
}
// 简写
function getDayName(day) {
const days = {
1: "Monday",
2: "Tuesday",
3: "Wednesday",
4: "Thursday",
5: "Friday",
6: "Saturday",
7: "Sunday",
};
return days[day] || "Invalid day";
}
15. 使用 filter 过滤数组中的所有假值
js
const removeFalsy = (arr) => arr.filter(Boolean);
// 返回: [1, 2, 3, "a", "s", 34]
removeFalsy([0, 1, false, 2, "", 3, "a", NaN, "s", 34]);
16. 强制参数,缺失报错
ES6 (2015) 可使用默认参数
js
function required(param) {
throw new Error(`${param} is required`);
}
function example(value = required("value")) {
console.log(value);
}
example(); // 抛出错误 "value is required"
总结
本篇文章介绍了 JavaScript 在不同版本 ECMAScript 规范中引入的常用特性,掌握这些特性可以让开发者更高效地编写 JavaScript 代码,提高代码的可维护性。
最后点赞👍 + 关注➕ + 收藏❤️ = 学会了🎉。