Pure function given strictly equal arguments yielding non-strictly equal results

后端 未结 6 667
执念已碎
执念已碎 2021-01-04 12:59

Below is a pure function f for which f(a) !== f(b) despite a === b (notice the strict equalities) for some values of a<

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-04 13:33

    1/+0 is Infinity and 1/-0 -Infinity, while +0 === -0.

    This can be explained by the fact that ECMA defines -0 to equal +0 as a special case, while in other operations these two values retain their different properties, which result in some inconsistencies.

    This is only possible because the language explicitly defines two non-equal values to be equal, that in fact are not.

    Other examples, if any, should be based on the same sort of artificial equality, and given http://ecma262-5.com/ELS5_HTML.htm#Section_11.9.6 there is no other such excention, so probably no other example of this.

    If it's of any use, we can ensure that 0 is not -0 by adding 0 to it:

    var f = function(x) {
       return 1 / (x + 0);
    }
    f(+0) === f(-0)
    

提交回复
热议问题