美文网首页
JavaScript中的数据类型转换特殊总结

JavaScript中的数据类型转换特殊总结

作者: 拾柒_aab0 | 来源:发表于2019-10-08 14:08 被阅读0次

    typeof类型转换

    console.log(typeof Number);//function
    console.log(typeof Object);//function
    console.log(typeof null);//object null代表空的对象
    console.log(typeof String);//function
    console.log(typeof Boolean);//function
    console.log(typeof undefined);//undefined
    console.log(typeof 0);//false
    console.log(typeof false);//boolean
    console.log(typeof true);//boolean
    console.log(typeof 1);//number
    console.log(typeof NaN);//number NaN是特殊的数值类型

    number转换

    console.log(Number(null));//0
    console.log(Number(0));//0
    console.log(Number(undefined));//NaN
    console.log(Number(false));//0
    console.log(Number(true));//1

    isNaN

    检测前先隐式转换一下看是否能转换为数值
    console.log(isNaN(0));//false
    console.log(isNaN(1));//false
    console.log(isNaN(null));//false能转化为0
    console.log(isNaN(undefined));//true
    console.log(isNaN(false));//false能转化为0
    console.log(isNaN(true));//false能转化为1
    console.log(isNaN('12'));//false

    Boolean类型转换

    console.log(Boolean(Number));//true
    console.log(Boolean(Object));//true
    console.log(Boolean(String));//true
    console.log(Boolean(Boolean));//true
    console.log(Boolean(' '));//true 不是空字符串
    console.log(Boolean(''));//false
    console.log(Boolean(null));//false
    console.log(Boolean(undefined));//false
    console.log(Boolean(0));//false
    console.log(Boolean(NaN));//false
    console.log(Boolean(false));//false

    比较

    console.log(0 == false);//true
    console.log(1 == true);//true
    console.log(null == undefined);//true
    console.log(null == false);//false
    console.log(null == 0);//false

    注:null和undefined是特殊的数据类型,null 和 undefined与其他类型比较返回的都是false,除非和自身比较 console.log(null == undefined);//true

    相关文章

      网友评论

          本文标题:JavaScript中的数据类型转换特殊总结

          本文链接:https://www.haomeiwen.com/subject/hkkppctx.html