zoukankan      html  css  js  c++  java
  • js中关于if() 和 == 的判断

    if的判断

    原理

    类型结果
    Undefined false
    Null false
    Boolean 直接判断
    Number +0, −0, 或者 NaN 为 false, 其他为 true
    String 空字符串为 false,其他都为 true
    Object true

    举例

    判断下面的输出内容

    if ("hello") {
        console.log("hello")
    }   //输出 hello
    
    if ("") {
        console.log('empty')
    } //没有输出
    
    if (" ") {
        console.log('blank')
    } //输出blank
    
    if ([0]) {
        console.log('array')
    } //输出array
    
    if('0.00'){
      console.log('0.00')
    } // 输出0.00
    

    ==的判断

    原理

    xy结果
    null undefined true
    Number String x == toNumber(y)
    Boolean (any) toNumber(x) == y
    Object String or Number toPrimitive(x) == y
    otherwise otherwise false

    toNumber

    typeResult
    Undefined NaN
    Null 0
    Boolean ture -> 1, false -> 0
    String "abc" -> NaN, “123” -> 123

    toPrimitive
    对于 Object 类型,先尝试调用 .valueOf 方法获取结果。 如果没定义,再尝试调用 .toString方法获取结果

    举例

    判断下面的输出内容

    "" == 0  //  true
    " " == 0  // true
    "" == true  // false
    "" == false  // true
    " " == true  // false
    
    !" " == true  // false
    !" " == false  // true
    "hello" == true  // false
    "hello" == false // false
    "0" == true  // false
    "0" == false  // true
    "00" == false  // true
    "0.00" == false  // true
    
    undefined == null  // true
    true == {}  // false
    [] == true  // false
    
    var obj = { 
      a: 0, 
      valueOf: function(){return 1} 
    } 
    
    obj == "[object Object]"  // false
    obj == 1  // true
    obj == true  // true


    作者:张柴柴
    链接:https://www.jianshu.com/p/a9c44c467f44
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 相关阅读:
    PAT (Advanced Level) 1086. Tree Traversals Again (25)
    PAT (Advanced Level) 1085. Perfect Sequence (25)
    PAT (Advanced Level) 1084. Broken Keyboard (20)
    PAT (Advanced Level) 1083. List Grades (25)
    PAT (Advanced Level) 1082. Read Number in Chinese (25)
    HDU 4513 吉哥系列故事――完美队形II
    POJ Oulipo KMP 模板题
    POJ 3376 Finding Palindromes
    扩展KMP
    HDU 2289 Cup
  • 原文地址:https://www.cnblogs.com/deepalley/p/14153644.html
Copyright © 2011-2022 走看看