JavaScript 古怪的弱类型==
运算符可以很容易地显示为不可传递的,如下所示:
var a = "16";
var b = 16;
var c = "0x10";
alert(a == b && b == c && a != c); // alerts true
我想知道是否有任何类似的技巧可以使用舍入误差,Infinity
或者NaN
应该显示===
为非传递性的,或者是否可以证明它确实是传递性的。
JavaScript 古怪的弱类型==
运算符可以很容易地显示为不可传递的,如下所示:
var a = "16";
var b = 16;
var c = "0x10";
alert(a == b && b == c && a != c); // alerts true
我想知道是否有任何类似的技巧可以使用舍入误差,Infinity
或者NaN
应该显示===
为非传递性的,或者是否可以证明它确实是传递性的。
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.
如果您查看规范(http://bclary.com/2004/11/07/#a-11.9.6),您会发现没有进行类型强制。此外,其他一切都非常简单,所以也许只有实现错误才会使其不可传递。
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