11

JavaScript 古怪的弱类型==运算符可以很容易地显示为不可传递的,如下所示:

var a = "16";
var b = 16;
var c = "0x10";
alert(a == b && b == c && a != c); // alerts true

我想知道是否有任何类似的技巧可以使用舍入误差,Infinity或者NaN应该显示===为非传递性的,或者是否可以证明它确实是传递性的。

4

3 回答 3

3

Javascript 中的===运算符似乎具有传递性。

NaN可靠地不同于NaN

>>> 0/0 === 0/0
false
>>> 0/0 !== 0/0
true

Infinity可靠地等于Infinity

>>> 1/0 === 1/0
true
>>> 1/0 !== 1/0
false

对象(哈希)总是不同的:

>>> var a = {}, b = {};
>>> a === b
false
>>> a !== b
true

And since the === operator does not perform any type coercion, no value conversion can occur, so the equality / inequality semantics of primitive types will remain consistent (i.e. won't contradict one another), interpreter bugs notwithstanding.

于 2011-10-01T20:24:00.160 回答
2

如果您查看规范(http://bclary.com/2004/11/07/#a-11.9.6),您会发现没有进行类型强制。此外,其他一切都非常简单,所以也许只有实现错误才会使其不可传递。

于 2011-10-01T20:19:10.993 回答
1

Assuming you have variable a,b, and c you can't be 100% certain as shown here. If someone is doing something as hackish as above in production, well then you probably have bigger problems ;)

var a = 1;
var b = 1;
Object.defineProperty(window,"c",{get:function(){return b++;}});

alert(a === b && b === c && a !== c); // alerts true
于 2011-10-01T20:56:05.093 回答