美文网首页饥人谷技术博客
js中if(xx)和 a==b 小结

js中if(xx)和 a==b 小结

作者: fanison | 来源:发表于2019-03-08 22:28 被阅读7次
// 题目1:如下代码输出什么?
if ("hello") {
  console.log("hello")
}

hello
注: "hello"为String,被转换为True
等同于 if (true) {console.log("hello")}

// 题目2:如下代码输出什么?
if ("") {
    console.log('empty')
}

undefined
注:""为空字符串,被转换为False

// 题目3:如下代码输出什么?
if (" ") {
    console.log('blank')
}

blank
注:" " 为String类型,因为除空字符串为false,其他都为true。

// 题目4:如下代码输出什么?
if ([0]) {
    console.log('array')
}

array
注:[0]为Object类型,被转换为True

if('0.00'){
    console.log('0.00')
  }

0.00
注: '0.00'为String类型,非空 为true

if(0.00){
    console.log('0.00')
  }

undefined
注: 0.00为Number类型,被转换为0,false

小结:对于括号里的表达式,会被强制转换为布尔类型

原理

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

a==b

**比较不同类型的数据时,相等运算符会先将数据进行类型转换,然后再用严格相等运算符比较。**

原理

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

toNumber

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

阮一峰 相等运算符

相关文章

  • js中if(xx)和 a==b 小结

    hello注: "hello"为String,被转换为True等同于 if (true) {console.lo...

  • js中关于if(xx)和 a==b

    if判断 在js中一般不使用if(变量)的方式使用if条件语句,容易产生你所不希望的结果,先来看看如下的代码 看了...

  • 2019-04-07

    JS中关于if(xx)与a==b的判断 if(xx)的判断 1.if(number) 当if中是number为+0...

  • 关于JS中if(xx)和 a==b的判断

    1. if结构 if结构先判断一个表达式的布尔值,然后根据布尔值的真伪,执行不同的语句。 基本形式 注意点:对于i...

  • JS中关于if(xx)和 a==b的判断

    一、JS中关于if(xxx)的判断: js是如何处理的?我们先来看几道测试题 以上题目代码的输出结果为: 题目1的...

  • 2018-03-14

    if(xx)和a==b的判断 在JS中,if语句是最常见的编程语句,语法为if(condition){//true...

  • JS中关于if(xx)和 a==b的类型转换

    if(XX)——不推荐该用法 语法:if(condition){statement} 以上condition可以是...

  • if(xx)和 a==b

    一.对于if()括号里的表达式会被强制转换为布尔类型。 判断原理如下: undefined --> false n...

  • if(xx)和 a==b

    一. if(xx)的判断 JavaScript 遇到预期为布尔值的地方(比如if语句的条件部分),就会将非布尔值的...

  • if(xx)和a==b

    参考自https://developer.mozilla.org/zh-CN/docs/Web/JavaScrip...

网友评论

    本文标题:js中if(xx)和 a==b 小结

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