Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...