Is there any value for what x === x returns false

2020-02-05 02:02发布

Is there any value for what x === x returns false without NaN?

For example:

> x = 1
1
> x === x
true
> x = {}
{}
> x === x
true
> x = new Date()
Wed Nov 13 2013 15:44:22 GMT+0200 (EET)
> x === x
true
> x = NaN
NaN
> x === x
false

I see that the only value where x === x returns false is when isNaN(x) === true.

Is there another value of x for what x === x returns false? An official reference would be welcome!

标签: javascript
2条回答
爷、活的狠高调
2楼-- · 2020-02-05 02:20

The spec lists the exact rules for strict equality.
There are no other such cases, unless you count +0 and -0.

The SameValue algorithm (used for validating changes to read-only defined properties) has no such exceptions.

查看更多
▲ chillily
3楼-- · 2020-02-05 02:23

The strict comparison between two equal non-NaN values will always be true (SLaks's answer correctly quotes the spec). However, it's possible for the expression x to change its value during the evaluation of the the equality. This can happen with property access when using accessor property descriptors (i.e., property getters):

foo = {};
Object.defineProperty(foo, "bar", {
    get: function() {
        return Math.random();
    }
})

foo.bar === foo.bar; // false

If you do this for the global object window (or global in Node), then you can see the x === x comparison fail for a global-scope variable:

Object.defineProperty(window, "bar", {
    get: function() {
        return Math.random();
    }
})

bar === bar; // false
查看更多
登录 后发表回答