JavaScript数据类型转换为布尔值的规则及数值分别为什么?

11 min read

当你将其他类型的值转换为布尔类型时,JavaScript 将根据以下规则进行转换:

  1. false 类型的值转换为 false,例如:false、0、空字符串("")、null、undefined、NaN。
  2. true 类型的值转换为 true,例如:true、1、任何非空字符串、任何对象,甚至是字符串 "false" 和 "0"。
  3. 对象、函数和数组类型的值永远转换为 true。

下面是各类型值转化为Boolean的结果:

  1. Boolean 类型:在布尔上下文中,Boolean true 转换为 true,Boolean false 转换为 false。
  2. Number 类型:如果值是 +0、-0、NaN 或者 null,则转换为 false,其他情况转换为 true。
  3. BigInt 类型:如果值是 0n,则转换为 false,其他情况转换为 true。
  4. String 类型:如果值是空字符串,则转换为 false,其他情况转换为 true。
  5. Null 类型:转换为 false。
  6. Undefined 类型:转换为 false。
  7. Object 类型:转换为 true。

举个例子:

Boolean(0)       // false
Boolean("")      // false
Boolean(undefined) // false
Boolean(null)     // false
Boolean(NaN)      // false

Boolean("0")      // true
Boolean("false")  // true
Boolean({})       // true
Boolean([])       // true
Boolean(function() { return true; }) // true