简写条件判断语句
如果仅在判断条件为 true 时才执行函数,则可以使用 && 简写。
// 普通写法
if (condition) {
doSomething();
}
// 简写
condition && doSomething();
将数字转换为字符串
const str = '404';
console.log(+str) // 404;
数组中过滤所有虚值
const myArray = [1, undefined, NaN, 2, null, '@denicmarko', true, 3, false];
console.log(myArray.filter(Boolean)); // [1, 2, "@denicmarko", true, 3]
妙用 includes
const myTech = 'JavaScript';
const techs = ['HTML', 'CSS', 'JavaScript'];
// 普通写法
if (myTech === 'HTML' || myTech === 'CSS' || myTech === 'JavaScript') {
// do something
}
// includes 写法
if (techs.includes(myTech)) {
// do something
}
逻辑运算符 ??
当其左侧操作数为空或未定义时返回其右侧操作数,否则返回其左侧操作数。
const foo = null ?? 'my school';
// 输出: "my school"
const baz = 0 ?? 42;
// 输出: 0