移除数组假值
可以使用 filter()
结合 Boolean
来简化移除数组假值操作。假值指的是在条件判断中被视为 false
的值,例如 null
、undefined
、空字符串(""
或 ''
)、0、NaN
和 false
。
let arr = [12, null, 0, 'xyz', null, -25, NaN, '', undefined, 0.5, false];
//传统写法
let filterArray = arr.filter(value => {
if(value) {
return value
};
}); // [12, 'xyz', -25, 0.5]
//简化写法
let filterArray = arr.filter(value => Boolean(value)); // [12, 'xyz', -25, 0.5]
//最简写法
let filterArray = arr.filter(Boolean); // [12, 'xyz', -25, 0.5]
Boolean
是 JavaScript 的内置构造函数,通过传递一个值给它,可以将该值转换为布尔值。在这种情况下,Boolean
构造函数作为回调函数传递给 filter()
方法,因此会将每个数组元素转换为布尔值。只有转换结果为真值的元素才会保留在新数组中。
注意:这种方式会将 0 也过滤掉,如果不需要过滤 0,需要进行额外的判断。
多值匹配:
对于多个值的匹配,可以将所有的值放入一个数组中,然后使用 indexOf(
) 方法进行检查。indexOf()
方法是 JavaScript 数组的一个内置方法,它用于返回指定元素在数组中第一次出现的位置索引。如果数组中不存在该元素,则返回 -1。
//传统写法
if ( value === 'one' || value === 'two' || value === 'three' ) {
// 逻辑处理
}
const arr = ['one','two','three'];
//简化写法1
if (arr.indexOf(value) >= 0) {
// ...
}
//简化写法2
if (arr.includes(value)) {
// ...
}
空值合并运算符
空值合并运算符(??
)用于为 null
或 undefined
的变量提供默认值。
const fetchUserData = () => {
return 'apple';
};
const data = fetchUserData();
//传统写法
const username = data !== null && data !== undefined ? data : 'banana';
//简化写法
const username = data ?? 'banana';
除此之外,还有一个空位合并赋值运算符(??=
),用于在变量为空(null
或 undefined
)时进行赋值操作。
let variable1 = null;
let variable2 = "banana";
//传统写法
if (variable1 === null || variable1 === undefined) {
variable1 = variable2;
}
//简化写法
variable1 ??= variable2;
??=
的写法更加简洁和易读。它首先检查变量 variable1
是否为 null
或 undefined
,如果是,则将它赋值为 variable2
的值。如果 variable1
已经有一个非空的值,那么赋值操作就不会发生。
逻辑或赋值运算符
逻辑或赋值运算符(||=
)用于为变量分配默认值。
let count;
//传统写法
if (!count) {
count = 0;
}
//简化写法
count ||= 0;
当 count
为假值(例如 undefined、null、false、0、NaN 或空字符串)时,逻辑或赋值运算符将 count
赋值为 0。否则,它会保留 count
的原始值。
数组查找
当对数组进行查找时,indexOf()
用于获取查找项的位置。如果未找到该项,则返回值为-1
。在JavaScript中,0被视为false
,而大于或小于0的数字被视为true
。因此,需要这样来写:
//传统写法
if(arr.indexOf(value) > -1) {
}
if(arr.indexOf(value) === -1) {
}
//简化写法
if(~arr.indexOf(value)) {
}
if(!~arr.indexOf(value)) {
}
位非(~)运算符对除了-1之外的任何值都返回一个"真"值。对其进行取反就是简单地使用!~
即可。