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

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

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

相关标签:
9条回答
  • 2020-11-22 10:57

    You can empty a JavaScript Array by referencing it to a new array, using list = [] or deleting the elements of the currently referenced array list.length = 0.

    Source: JavaScript Empty Array

    0 讨论(0)
  • 2020-11-22 11:00

    None of the above helped me, when trying to use the knockout.js mapping plugin, perhaps since an "empty array" isn't really empty.

    I ended up using: data-bind="if: arr().length" which did the trick.

    This is specific to knockout, not the OP's question, but maybe it will help someone else browsing here in a similar situation.

    0 讨论(0)
  • 2020-11-22 11:04

    Regarding the line:

    if (arr == false) console.log("It's false!");
    

    Maybe these will help:

    console.log(0 == false) // true
    console.log([] == 0) // true
    console.log([] == "") // true
    

    What I believe is happening is that the boolean false is coerced to 0 for comparison with an object (the left-hand side). The object is coerced to a string (the empty string). Then, the empty string is coerced into a number, as well, namely zero. And so the final comparison is 0 == 0, which is true.

    Edit: See this section of the spec for details on exactly how this works.

    Here's what's happening, starting at rule #1:

    1. If Type(x) is different from Type(y), go to step 14.

    The next rule that applies is #19:

    19. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).

    The result of ToNumber(false) is 0, so we now have:

    [] == 0
    

    Again, rule #1 tells us to jump to step #14, but the next step that actually applies is #21:

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

    The result of ToPrimitive([]) is the empty string, so we now have:

    "" == 0
    

    Again, rule #1 tells us to jump to step #14, but the next step that actually applies is #17:

    17. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x)== y.

    The result of ToNumber("") is 0, which leaves us with:

    0 == 0
    

    Now, both values have the same type, so the steps continue from #1 until #7, which says:

    7. If x is the same number value as y, return true.

    So, we return true.

    In brief:

    ToNumber(ToPrimitive([])) == ToNumber(false)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 11:07

    To supplement Wayne's answer and to try to explain why ToPrimitive([]) returns "", it's worth considering two possible types of answers to the 'why' question. The first type of answer is: "because the specification says this is how JavaScript will behave." In the ES5 spec, section 9.1, which describes the result of ToPrimitive as a default value for an Object:

    The default value of an object is retrieved by calling the [[DefaultValue]] internal method of the object, passing the optional hint PreferredType.

    Section 8.12.8 describes the [[DefaultValue]] method. This method takes a "hint" as an argument, and the hint can be either String or Number. To simplify the matter by dispensing with some details, if the hint is String, then [[DefaultValue]] returns the value of toString() if it exists and returns a primitive value and otherwise returns the value of valueOf(). If the hint is Number, the priorities of toString() and valueOf() are reversed so that valueOf() is called first and its value returned if it's a primitive. Thus, whether [[DefaultValue]] returns the result of toString() or valueOf() depends on the specified PreferredType for the object and whether or not these functions return primitive values.

    The default valueOf() Object method just returns the object itself, which means that unless a class overrides the default method, valueOf() just returns the Object itself. This is the case for Array. [].valueOf() returns the object [] itself. Since an Array object is not a primitive, the [[DefaultValue]] hint is irrelevant: the return value for an array will be the value of toString().

    To quote David Flanagan's JavaScript: The Definitive Guide, which, by the way, is a superb book that should be everyone's first place to get answers to these types of questions:

    The details of this object-to-number conversion explain why an empty array converts to the number 0 and why an array with a single element may also convert to a number. Arrays inherit the default valueOf() method that returns an object rather than a primitive value, so array-to-number conversion relies on the toString() method. Empty arrays convert to the empty string. And the empty string converts to the number 0. An array with a single element converts to the same string that that one element does. If an array contains a single number, that number is converted to a string, and then back to a number.

    The second type of answer to the "why" question, other than "because the spec says", gives some explanation for why the behavior makes sense from the design perspective. On this issue I can only speculate. First, how would one convert an array to a number? The only sensible possibility I can think of would be to convert an empty array to 0 and any non-empty array to 1. But as Wayne's answer revealed, an empty array will get converted to 0 for many types of comparisons anyway. Beyond this, it's hard to think of a sensible primitive return value for Array.valueOf(). So one could argue that it just makes more sense to have Array.valueOf() be the default and return the Array itself, leading toString() to be the result used by ToPrimitive. It just makes more sense to convert an Array to a string, rather than a number.

    Moreover, as hinted by the Flanagan quote, this design decision does enable certain types of beneficial behaviors. For instance:

    var a = [17], b = 17, c=1;
    console.log(a==b);      // <= true
    console.log(a==c);      // <= false
    

    This behavior allows you to compare a single-element array to numbers and get the expected result.

    0 讨论(0)
  • 2020-11-22 11:08

    An array with elements (regardless if 0, false or another empty array), always resolves to true using Abstract Equality Comparison ==.

    1. [] == false; // true, because an empty array has nothing to be truthy about
    2. [2] == false; // false because it has at least 1 item
    3. [false] == false; // also false because false is still an item
    4. [[]] == false; // false, empty array is still an item
    

    But using a Strict Equality Comparison ===, you are attempting to evaluate the variable's content as well as its data type that is why:

    1. [] === false; // false, because an array (regardless of empty or not) is not strictly comparable to boolean `false`
    2. [] === true; // false, same as above, cannot strictly compare [] to boolean `true`
    3. [[]] === false; // true, because see #1
    
    0 讨论(0)
提交回复
热议问题