Empty arrays seem to equal true and false at the same time

前端 未结 9 2170
别跟我提以往
别跟我提以往 2020-11-22 10:23

Empty arrays are true but they\'re also equal to false.

9条回答
  •  逝去的感伤
    2020-11-22 11:07

    You're testing different things here.

    if (arr) called on object (Array is instance of Object in JS) will check if the object is present, and returns true/false.

    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 "".

    This is because toString called on Array returns Array.join(), and empty string is one of falsy values in JavaScript.

提交回复
热议问题