因此,我知道:null、" "、undefined,0, NaN将返回false,JS中的所有其他值都将是true,但为什么:
console.log([] - 1) // -1 (it`s mean that [] = 0 (value of false?)
console.log([] - []) // 0 (wtf?),[] = 1?
if([]) console.log('true') // true
console.log(null - 1) // -1
if(null) console.log('true') // (false, no output)
谁,你能解释一下发生了什么事吗?
发布于 2019-07-26 18:26:11
-操作符将操作数强制到Number。if (expression)胁迫表达到Boolean。
所以让我们看看[]和null强迫Number和Boolean做什么.
console.log(' [] as Number: ', Number([]) ); //0
console.log(' [] as Boolean:', Boolean([]) ); //true
console.log('null as Number: ', Number(null) ); //0
console.log('null as Boolean:', Boolean(null) ); //false
通过这些信息,您可以清楚地了解您的每个表达式是如何记录相应的值的。
// Output | Evaluated As
console.log([] - 1) // -1 | (0 - 1)
console.log([] - []) // 0 | (0 - 0)
if([]) console.log('true') // true | ( if(true) )
console.log(null - 1) // -1 | (0 - 1)
if(null) console.log('true') // (none) | ( if(false) )
发布于 2019-07-26 16:48:50
这是一个算术表达式。根据ECMAScript语言规范,在算术表达式中,不同类型的转换如下:

在表达式中,array ([])被认为是object,并相应地转换为。
全参考here.
https://stackoverflow.com/questions/57223968
复制相似问题