Boolean evaluation of JavaScript arrays

丶灬走出姿态 提交于 2019-12-10 15:44:34

问题


I ran across an interesting bug the other day. I was testing an array to see if it evaluated to Boolean false, however just directly evaluating it always returned true:

> !![]
  true

Okay, so basically any array I put in there will be true regardless, right? I run this in the JavaScript console just for fun:

> [] == true
  false

What is going on here?


回答1:


It has to do with the The Abstract Equality Comparison Algorithm versus the algorithm used to tranform a value to a boolean.

By looking at the spec, we can see that the point number 9. is the only one that defines what should be happening when Type(left side value) is Object. However it's specifying that the right side value has to be either String or Number.

9 . If Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x) == y.

Looking at [] == true:

typeof [] is 'object' so we are fine, but typeof true is not 'string' or 'number', it is 'boolean', so it fallback to the last statement, point number 10.

10 . Return false.

However !![] translates into !!Boolean([]), and since [] is a thruty value (objects are), it's the same as writing !!true, which returns true.



来源:https://stackoverflow.com/questions/19034155/boolean-evaluation-of-javascript-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!