js && 和||的用法

如果只在变量为 true 时才调用函数,可以使用 && 操作符。

//Longhand 
if (test1) {
 callMethod(); 
} 
//Shorthand 
test1 && callMethod();

当我们创建了新变量,有时候想要检查引用的变量是不是为非 null 或 undefined。JavaScript 确实有一个很好的快捷方式来实现这种检查。

// Longhand
if (test1 !== null || test1 !== undefined || test1 !== '') {
    let test2 = test1;
}
// Shorthand
let test2 = test1 || '';

 

posted @ 2022-01-02 16:34  程序员小明1024  阅读(165)  评论(0编辑  收藏  举报