JavaScript 代码优化技巧
1. 含有多个条件的 if 语句
//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
//logic
}
//shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
//logic
}
includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false。
2. If … else 的缩写法
// Longhand
let test;
if (x > 100) {
test = true;
} else {
test = false;
}
// Shorthand
let test = (x > 10) ? true : false;
条件运算符(三元运算符):
语法形式:布尔表达式 ? 表达式1 :表达式2
运算过程:如果布尔表达式的值为 true ,则返回 表达式1 的值,否则返回 表达式2 的值
3. 聚合运算符
聚合运算符:xx ?? xx
意义:如果左值为 null 或 undefined,就返回右值。默认返回左值。
const test= null ?? 'default';
console.log(test);
// expected output: "default"const
test1 = 0 ?? 2;
console.log(test1);
// expected output: 0
4. 同时为多个变量赋值
//Longhand
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//Shorthand
let [test1, test2, test3] = [1, 2, 3];
5. 判断变量是否存在的缩写法
// Longhand
if (test1 === true) or if (test1 !== "") or if (test1 !== null)
// Shorthand
//it will check empty string,null and undefined too
if (test1){}
6. 用于多个条件的与(&&)运算符
// 变量为 true 时调用一个函数
//Longhand
if (test1) {
callMethod();
}
//Shorthand
test1 && callMethod();
7. for… 循环缩写法
// Longhand
for (var i = 0; i < testData.length; i++) {
console.log(i,testData[i]);
}
// Shorthand
for (let i in testData){
console.log(testData[i]);
}
// or
// for (let j of testData){
// console.log(j);
// }
8. 找出一个数组中最大和最小的值
const arr = [1, 2, 3];
Math.max(…arr); // 3
Math.min(…arr); // 1
9. Object.values()
ES8 新增新特性
const data = { test1: 'abc', test2: 'cde' };
const arr = Object.values(data);
console.log(arr);
// [ 'abc', 'cde']
10. 获取一个随机布尔值 (true/false)
const randomBoolean = () => Math.random() >= 0.5;
console.log(randomBoolean());
// Result: a 50/50 change on returning true of false
Math.random()
该方法将在 0 和 1 之间创建一个随机数,之后我们检查它是否高于或低于 0.5。这意味着得到真或假的几率是 50%/50%。