美文网首页
js 类型判断及 '==' 操作符

js 类型判断及 '==' 操作符

作者: saxon_y | 来源:发表于2021-01-15 19:27 被阅读0次
    js 类型判断

    js 八种数据类型:
    Undefined, String, Symbol, Object, Number, Null, Boolean, BigInt
    取首字母记忆:u so nb

    typeof 返回类型:
    undefined, string, symbol, object, number, boolean, bigint, function

    typeof null //"object"
    typeof [] //"object"
    typeof {} //"object"
    typeof NaN //"number"
    typeof function(){} //"function"
    typeof (() => {}) //"function"
    typeof BigInt(1) //"bigint"
    typeof Symbol() //"symbol"
    typeof "" //"string"
    typeof saxon_y //"undefined"
    typeof undefined //"undefined"
    typeof !null //"boolean"
    

    如果要判断数组,考虑到 instanceof 某些IE版本浏览器不兼容,下面这种方法兼容性相对较好:

    if(typeof Array.isArray==="undefined")
    {
    Array.isArray = function(arr){
            return Object.prototype.toString.call(arr)==="[object Array]"
        };  
    }
    
    js 中的 =====

    在使用 == 做判断时 js 做了隐式类型转换,比如 "1" == 1 返回 true,而 === 则不会类型转换,会首先判断两个值的类型是否相同,如果相同再进行比较,故 “1” === 1 返回 false

    具体转换逻辑大致分四种情况(同类型比较除外,如:number == number ):

    1. object == string,先接将 object 类型转换为 string 类型后再进行比较
    2. object == (number/boolean),先将 object 类型转换为 string 类型,再将 string 类型转换为 number 类型,和另一个值比较,如果另一个值不是 number 类型先将其转换为 number 类型
    3. 其他比较如:number == booleanstring == boolean,将不是 number 类型的值转换为 number 类型再做比较
    4. null == undefined ==> truenull === undefined ==> falsenull 或者 undefined 和其他任何的数据类型比较都返回 false
    [1,2] == '1,2' //true,[1,2].toString() ==> "1,2"
    (function(){console.log('hello')}) == "function(){console.log('hello')}" //true
    [1] == true //true,[1].toString() ==> "1",Number("1") ==> 1,Number(true) ==> 1
    [12] == 12 //true,[12].toString() ==> "12",Number("12") ==> 12
    

    常见的类型转换:

    Number(false) //0
    Number(true) //1
    Number("") //0
    [].toString() //""
    Boolean(+0) //false
    Boolean(-0) //false
    Boolean(+2) //true
    Boolean(-2) //true,所有非0数转换boolean都是true,NaN除外
    Boolean(BigInt(1)) //true
    Boolean(BigInt(0)) //false
    

    注意点:
    NaN == NaN ==> false
    ! 取反操作:
    !! 转换 boolean 值,除了 0 NaN "" null undefined 其他都为 true

    面试常考题:

    [] == false //true,先将 [] 转为字符串 "" ,再将 "" 转为数字 0,false也转换为数字 0,故返回 true
    !![] == false //false,因 ! 优先级比 == 高,所以先将计算 !![] 为true,true == false,故返回false
    

    点赞、收藏的人已经开上兰博基尼了 (´▽`ʃ♡ƪ)

    转载请注明出处!!!(https://www.jianshu.com/p/1baaf97d0b1a)

    相关文章

      网友评论

          本文标题:js 类型判断及 '==' 操作符

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