文章目录
-
-
- 1. 带有多个条件的 if 语句
- 2. 简化 if true...else
- 3. 声明变量
- 4. null、undefined 和空值检查
- 5. null 检查和默认赋值
- 6. undefined 检查和默认赋值
- 7. 给多个变量赋值
- 8. 简便的赋值操作符
- 9. if 判断值是否存在
- 10. 用于多个条件判断的 && 操作符
- 11. for each 循环
- 12. 比较后返回
- 13. 箭头函数
- 14. 简短的函数调用
- 15. switch 简化
- 16. 隐式返回
- 17. 指数表示法
- 18. 默认参数值
- 19. 延展操作符简化
- 20. 模板字面量
- 21. 跨行字符串
- 22. 对象属性赋值
- 23. 将字符串转成数字
- 24. 解构赋值
- 25. 数组 find 简化
- 26. 条件查找简化
- 27. indexOf 的按位操作简化
- 28. Object.entries()
- 29. Object.values()
- 30. 双重按位操作
- 31. 重复字符串多次
- 32. 查找数组的最大值和最小值
- 33. 获取字符串的字符
- 34. 指数幂简化
-
你可能做了很长时间的 JavaScript 开发,但有时候你可能没有使用最新的 JavaScript 特性或技巧,这些特性和技巧可以在不需要编写额外代码的情况下解决你的问题。它们可以帮助你写出干净且优化的 JavaScript 代码。
1. 带有多个条件的 if 语句
把多个值放在一个数组中,然后调用数组的 includes 方法。
//longhand
if (x === ‘abc’ || x === ‘def’ || x === ‘ghi’ || x ===‘jkl’) {
//logic
}
//shorthand
if ([‘abc’, ‘def’, ‘ghi’, ‘jkl’].includes(x)) {
//logic
}
2. 简化 if true…else
对于不包含大逻辑的 if-else 条件,可以使用下面的快捷写法。我们可以简单地使用三元运算符来实现这种简化。
// Longhand
let test: boolean;
if (x > 100) {
test = true;
} else {
test = false;
}
// Shorthand
let test = (x > 10) ? true : false;
//or we can use directly
let test = x > 10;
console.log(test);
如果有嵌套的条件,可以这么做。
let x = 300,
test2 = (x > 100) ? ‘greater 100’ : (x < 50) ? ‘less 50’ : ‘between 50 and 100’;
console.log(test2); // “greater than 100”
3. 声明变量
当我们想要声明两个具有相同的值或相同类型的变量时,可以使用这种简写。
//Longhand
let test1;
let test2 = 1;
//Shorthand
let test1, test2 = 1;
4. null、undefined 和空值检查
当我们创建了新变量,有时候想要检查引用的变量是不是为非 null 或 undefined。JavaScript 确实有一个很好的快捷方式来实现这种检查。
// Longhand
if (test1 !== null || test1 !== undefined || test1 !== ‘’) {
let test2 = test1;
}
// Shorthand
let test2 = test1 || ‘’;
两个问号判空
5. null 检查和默认赋值
let test1 = null,
test2 = test1 || ‘’;
console.log(“null check”, test2); // output will be “”
6. undefined 检查和默认赋值
let test1 = undefined,
test2 = test1 || ‘’;
console.log(“undefined check”, test2); // output will be “”
一般值检查
let test1 = ‘test’,
test2 = test1 || ‘’;
console.log(test2); // output: ‘test’
另外,对于上述的 4、5、6 点,都可以使用?? 操作符。
如果左边值为 null 或 undefined,就返回右边的值。默认情况下,它将返回左边的值。
const test= null ?? ‘default’;
console.log(test);
// expected output: “default”
const test1 = 0 ?? 2;
console.log(test1);
// expected output: 0
7. 给多个变量赋值
当我们想给多个不同的变量赋值时,这种技巧非常有用。
//Longhand
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//Shorthand
let [test1, test2, test3] = [1, 2, 3];
8. 简便的赋值操作符
在编程过程中,我们要处理大量的算术运算符。这是 JavaScript 变量赋值操作符的有用技巧之一。
// Longhand
test1 = test1 + 1;
test2 = test2 - 1;
<