Is an empty array strictly equal to anything in JavaScript?

后端 未结 1 1259
情歌与酒
情歌与酒 2020-12-06 19:54

I did a series of tests for different array values:

Tests:

x === 0
x === \'\'
x === false
x === undefined
x === NaN
x === null
x ===         


        
相关标签:
1条回答
  • 2020-12-06 20:35

    An empty array is strictly equal only to itself. More properly, an expression that evaluates to a reference to some particular empty array is only strictly equal to another reference to that same array.

    That holds for any sort of object, not just arrays, and not just empty arrays. There's no built-in way to provide your own special behavior for equality comparisons with ===.

    Comparisons with == are another story because of the type conversions that are implicitly performed. It's still true, however, than object comparisons even with == (that is, when no type conversions are performed) follow the same rule: a reference to an object is only equal to another reference to the same object.

    Note also that

    [] === []
    

    is false because those are two different empty arrays. Similarly,

    [1, 2] === [1, 2]
    

    is false, as is

    {a: "hello"} === {a: "hello"}
    

    Every array or object initializer expression creates a unique object, so even though they look the same, they're not equal under the rules of JavaScript === comparison.

    0 讨论(0)
提交回复
热议问题