当谈到 JavaScript 的小技巧时,常见的技巧有短路求值、三元表达式等。但本文将介绍更多不常见的技巧,可以提高编码效率,减少代码量。
1. 使用 null 判断空值
当需要判断一个变量是否为空值时,我们通常会采用如下方式:
if (x === '' || x === null || x === undefined) {
// do something
}
但实际上,null
和 undefined
是 JavaScript 中的 Falsy 值,因此我们可以利用这个特点,对上述判断条件进行简化:
if (!x) {
// do something
}
这样,我们只需要判断变量是否为 Falsy 值,即可判断变量是否为空值。
2. 使用 destructuring 减少代码量
当需要从对象或数组中提取多个值时,我们通常需要写很多代码:
const obj = {
name: 'John',
age: 30,
sex: 'male'
};
const name = obj.name;
const age = obj.age;
const sex = obj.sex;
const arr = [1, 2, 3];
const first = arr[0];
const second = arr[1];
const third = arr[2];
但我们可以使用 Destructuring(解构赋值)语法,将上述代码简化为:
const { name, age, sex } = {
name: 'John',
age: 30,
sex: 'male'
};
const [first, second, third] = [1, 2, 3];
通过 Destructuring 语法,我们可以一次性从对象或数组中提取多个值,大大减少了代码量。
希望以上两个小技巧能对你提升编码效率、幸福度有所帮助!
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:JS 中可以提升幸福度的小技巧(可以识别更多另类写法) - Python技术站