空陣列是true? 空陣列==false

  • 1367
  • 0
  • ES6
  • 2018-08-27

array

Empty arrays seem to equal true and false at the same time
https://stackoverflow.com/questions/5491605/empty-arrays-seem-to-equal-true-and-false-at-the-same-time

if (arr) 會被呼叫,是因為object,Array is instance of Object in JS
In JavaScript, all objects are truthy , even new Boolean(false), empty arrays and empty objects
 

Boolean(new Boolean(false))
//true

Boolean([])
//true

Boolean({})
//true

When you call if (arr == false) you compare values of this object and the primitive false value. Internally, arr.toString() is called, which returns an empty string "".
但當你是在比較value時, Array裡的 toString會被呼叫

This is because toString called on Array returns Array.join(), and empty string is one of falsy values in JavaScript.
當Array的 toString被呼叫, 會回傳Array.join( ),然後空字串就被回傳,所以 == false 就成立了

The following values are always falsy:

  • false.
  • 0 (zero)
  • ' ' or " " (empty string)
  • null.
  • undefined.
  • NaN (e.g. the result of 1/0 )