JavaScript操作符优雅运用



三目运算符

    if (hasMoney) {
        console.log('今天吃肉');
    } else {
        console.log('今天吃素');
    }
    hasMoney ? console.log('今天吃肉') : console.log('今天吃素');
    let weekendPlan = hasMoney ? '今天吃肉' : '今天吃素';

逻辑与操作符 &&

    if (hasMoney) {
        console.log('今天是工作日');
    }
    hasMoney ? console.log('今天是工作日') : undefined;
    hasMoney && console.log('今天是工作日');
    true && console.log('It is true');                         // It is true
    true && false && console.log('It is true');                // 返回 false
    true && 0 && console.log('It is true');                    // 返回 0
    true && undefined == null && console.log('It is true');    // It is true, 表达式undefined == null的运算结果为true
    true && undefined === null && console.log('It is true');   // 返回 false, 表达式undefined === null的运算结果为false

逻辑或操作符 ||

// 当自身为undefined时,赋值为0,否则还是赋值为自身
    val = val !== undefined ? val : 0;
val = val || 0;
// ES5设置函数默认值
    function testFunc(arg1) {
        arg1 = arg1 || 1;

        // do something else
    }

    let a = 1,
        b = 2,
        c = null;

    console.log(a || b || c);         // 1
    console.log(0 || b || c);         // 2
    console.log(0 || false || c);     // null

按位取反操作符 ~

    let arr = ['we', 'are', 'the', 'BlackGold', 'team'];

    arr.includes('the') && console.log('in');      // in

    let arr = ['we', 'are', 'the', 'BlackGold', 'team'];

    arr.includes(element => element === 'the') && console.log('in');     // 返回false

    let arr = ['we', 'are', 'the', 'BlackGold', 'team'];

    arr.findIndex(element => element === 'the') !== -1 && console.log('in');      // in

    let arr = ['we', 'are', 'the', 'BlackGold', 'team'];

    ~arr.findIndex(element => element === 'we') && console.log('in');      // in
    ~arr.findIndex(element => element === 'the') && console.log('in');      // in

    console.log(~-1);       // 0 转换为Boolean值即为false
    console.log(~0);        // -1 转换为Boolean值即为true
    console.log(~1);        // -2 转换为Boolean值即为true

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值