JavaScript(4) - JS数据结构和算法 1

JavaScript中的真假值

先来看一个表格:

数值类型转化成布尔值
undefinedfalse
nullfalse
布尔值true是true,false是false
数字+0,-0,NaN都是false,其他都是true
字符串如果字符串是空的(长度为0)即为false,其他都是true
对象true

下面一段代码:

    var myObj = {
        name: 'illuSioN4ng'
    };
    console.log(myObj);

    function testTruthy(val){
        return val ? console.log('true') : console.log('false');
    }

    console.log('==================');
    testTruthy(true);   //      true
    testTruthy(false);  //      false
    testTruthy(new Boolean(false));//   对象始终为true

    console.log('==================');
    testTruthy('');     //      false
    testTruthy('illuSioN4ng');//true
    testTruthy(new String(''));//   对象始终为true

    console.log('==================');
    testTruthy(1);      //      true
    testTruthy(-1);     //      true
    testTruthy(0);      //      false
    testTruthy(-0);     //      false
    testTruthy(NaN);    //      false
    testTruthy(new Number(NaN));//   对象始终为true

    console.log('==================');
    testTruthy({});//   对象始终为true
    testTruthy(myObj);  //      true
    testTruthy(myObj.name);//   true
    testTruthy(myObj.height);// false
    console.log('==================');
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值