在 JavaScript 中其他值到布尔值的转换遵循以下规则1.Falsy 值转换为false的值以下 6 个值在布尔上下文中会被转换为falsefalse→false0和-0以及0nBigInt →false空字符串 →falsenull→falseundefined→falseNaN→false2.Truthy 值转换为true的值除了上述 6 个 Falsy 值之外的所有值都会转换为true非空字符串0、 空格、false→true非零数字-1、1、Infinity→true对象包括空对象、空数组{}、[]、function(){}→trueSymbolSymbol()→trueBigInt非零值1n→true转换方式隐式转换在条件语句中if(value){// value 为 truthy 时执行}if(!value){// value 为 falsy 时执行}valueother;// 逻辑与value||other;// 逻辑或value?a:b;// 三元运算符显式转换Boolean(value)// Boolean() 函数!!value// 双重取反常见示例Boolean(0)// falseBoolean(1)// trueBoolean()// falseBoolean(hello)// trueBoolean(null)// falseBoolean(undefined)// falseBoolean(NaN)// falseBoolean({})// trueBoolean([])// trueBoolean([0])// true数组本身是对象Boolean(false)// falseBoolean(true)// trueBoolean(0)// true非空字符串Boolean( )// true空格也是非空字符串Boolean(0n)// falseBigInt 零Boolean(1n)// true注意事项空数组[]是 truthy但[] false为true因为[]转为数字是0空对象{}是 truthy字符串0和false是 truthy因为它们是非空字符串在条件判断中只有那 6 个 Falsy 值会返回false其他所有值都是true
JavaScript 其他值到布尔值的转换规则是什么?
在 JavaScript 中其他值到布尔值的转换遵循以下规则1.Falsy 值转换为false的值以下 6 个值在布尔上下文中会被转换为falsefalse→false0和-0以及0nBigInt →false空字符串 →falsenull→falseundefined→falseNaN→false2.Truthy 值转换为true的值除了上述 6 个 Falsy 值之外的所有值都会转换为true非空字符串0、 空格、false→true非零数字-1、1、Infinity→true对象包括空对象、空数组{}、[]、function(){}→trueSymbolSymbol()→trueBigInt非零值1n→true转换方式隐式转换在条件语句中if(value){// value 为 truthy 时执行}if(!value){// value 为 falsy 时执行}valueother;// 逻辑与value||other;// 逻辑或value?a:b;// 三元运算符显式转换Boolean(value)// Boolean() 函数!!value// 双重取反常见示例Boolean(0)// falseBoolean(1)// trueBoolean()// falseBoolean(hello)// trueBoolean(null)// falseBoolean(undefined)// falseBoolean(NaN)// falseBoolean({})// trueBoolean([])// trueBoolean([0])// true数组本身是对象Boolean(false)// falseBoolean(true)// trueBoolean(0)// true非空字符串Boolean( )// true空格也是非空字符串Boolean(0n)// falseBigInt 零Boolean(1n)// true注意事项空数组[]是 truthy但[] false为true因为[]转为数字是0空对象{}是 truthy字符串0和false是 truthy因为它们是非空字符串在条件判断中只有那 6 个 Falsy 值会返回false其他所有值都是true