javascript 中'&&','||'和'??'小记

433 阅读1分钟

学习时发现大佬使用的||和我所认知的||有点歧义深入了解,故有此记

boolean转换

Boolean( null )          // false 
Boolean( undefined )     // false 
Boolean( NaN )           // false 
Boolean( 0 )             // false 
Boolean( "" )            // false 
Boolean( -123 )          // true 
Boolean( 123 )           // true 
Boolean( "string" )      // true 
Boolean( [] )            // true 
Boolean( [1,2,3] )       // true 
Boolean( {} )            // true

使用Boolean(value)方法可以强制转换任意值为boolean类型;除了undefined、null 、+0、-0、NaN、""六个值,其他都是自动转为true

&&运算结果

console.log( true && false )                   // false 
console.log( true && NaN )                     // NaN 
console.log( true && null )                    // null 
console.log( true && [] )                      // [] 
console.log( 0 && [] )                         // 0 
console.log( true && "AAA" && undefined )      // undefined 
console.log( true && "AAA" && "BBB" )          // BBB 
console.log( false && "AAA" && "BBB" )         // false

&&运算的结果取决于第一个其 Boolean(value) 转换结果为 false 的值;若全部皆为 true,则结果为最后一个值。

||运算结果


console.log( true || false )               // true 
console.log( true || NaN )                 // true 
console.log( true || null )                // true 
console.log( true || [] )                  // true 
console.log( 0 || [] )                     // [] 
console.log( true || "AAA" || undefined )  // true 
console.log( true || "AAA" || "BBB" )      // true 
console.log( false || "AAA" || "BBB" )     // "AAA"

||运算的结果也不一定为布尔类型,其结果取决于第一个其 Boolean(value) 结果为 true 的值,若全部为 false,则结果为最后一个元素的值

??运算结果

console.log(true ?? 'aaa')              //true
console.log(false ?? 'aaa')             //false
console.log([] ?? 'aaa')                //[]
console.log(undefined ?? 'aaa')         //aaa
console.log(null ?? 'aaa')              //aaa
console.log(true ?? 'aaa' ?? 'bbb')     //true
console.log(true ?? false ?? 'aaa')     //true
console.log(null ?? undefined ?? 'aaa') //aaa
console.log(null ?? 'aaa' ?? 'bbb')     //aaa

??运算结果只有当左侧为null和undefined时,才会返回右侧的数