7

I have read the MDN page on the "Object.is" method. It gives an alternative code for the browsers that do not provide this method:

if (!Object.is) {
    Object.is = function(v1, v2) {
        if (v1 === 0 && v2 === 0) {
            return 1 / v1 === 1 / v2;
        }
        if (v1 !== v1) {
            return v2 !== v2;
        }
        return v1 === v2;
    };
}

The question is simple: when can the second "if" be true ?

Thank you for your attention.

4

2 回答 2

4

It kinda is written in the same article:

This is also not the same as being equal according to the === operator. The === operator (and the == operator as well) treats the number values -0 and +0 as equal, and it treats Number.NaN as not equal to NaN.

The logic is that NaN !== NaN is the only case in which the !== operator returns true on the same variable, so it must be about NaN comparison. It then does the same check on v2 and returns true of false based on the outcome: if v2 comparison is true, it's about NaN compared to NaN so return true, if not then return false because NaN is never the same as something that isn't NaN.

于 2014-01-31T14:37:37.127 回答
0

Be aware, that we have more than only 1 NaN:

var notNaN = new DataView(new Uint8Array([0x7f, 0xf8,0,0,0,0,0,1]).buffer).getFloat64(0)
Object.is(notNaN, NaN) // true

const byteOf = (number, index) => {let v = new DataView(new ArrayBuffer(8)); v.setFloat64(0, number); return v.getUint8(index);}

byteOf(NaN, 7) // 0
byteOf(notNaN, 7) // 1

So there are two distinguishable values, but Object.is() says, they are the same

于 2019-11-12T16:29:19.890 回答