JavaScript操作符优雅运用

版权声明:署名-非商业性使用 转载请保留原文链接及作者。 https://blog.csdn.net/qq_40413396/article/details/85235156


三目运算符

    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

猜你喜欢

转载自blog.csdn.net/qq_40413396/article/details/85235156
今日推荐