你真得懂Javascript中的==等于运算符吗?

var i = 2;Number.prototype.valueOf = function() {return i++;};var a = new Number( 42 );if (a == 2 && a == 3) {console.log( "Yep, this happened." );

}

============================

"0" == null; // false"0" == undefined; // false"0" == false; // true — UH OH!"0" == NaN; // false"0" == 0; // true"0" == ""; // false

false == null; // falsefalse == undefined; // falsefalse == NaN; // falsefalse == 0; // true — UH OH!false == ""; // true — UH OH!false == []; // true — UH OH!false == {}; // false

"" == null; // false"" == undefined; // false"" == NaN; // false"" == 0; // true — UH OH!"" == []; // true — UH OH!"" == {}; // false

0 == null; // false0 == undefined; // false0 == NaN; // false0 == []; // true — UH OH!0 == {}; // false

[] == ![]; // true

2 == [2]; // true"" == [null]; // true

0 == "\n"; // true

var a = null;var b = Object( a ); // same as `Object()`a == b; // falsevar c = undefined;var d = Object( c ); // same as `Object()`c == d; // falsevar e = NaN;var f = Object( e ); // same as `new Number( e )`e == f; // false

======================================================

ES5规范中的解释:

Comparing: objects to nonobjectsIf an object/function/array is compared to a simple scalar primitive(string, number, or boolean), the ES5 spec says in clauses11.9.3.8-9:1. If Type(x) is either String or Number and Type(y) is Object,return the result of the comparison x == ToPrimitive(y).2. If Type(x) is Object and Type(y) is either String or Number,return the result of the comparison ToPrimitive(x) == y.

Comparing: nulls to undefinedsAnother example of implicit coercion can be seen with == looseequality between null and undefined values. Yet again quoting theES5 spec, clauses 11.9.3.2-3:1. If x is null and y is undefined, return true.2. If x is undefined and y is null, return true.

Comparing: anything to boolean1. If Type(x) is Boolean, return the result of the comparisonToNumber(x) == y.2. If Type(y) is Boolean, return the result of the comparison x ==ToNumber(y).

Comparing: strings to numbers

1. If Type(x) is Number and Type(y) is String, return the result ofthe comparison x == ToNumber(y).2. If Type(x) is String and Type(y) is Number, return the result ofthe comparison ToNumber(x) == y.

==============================直观的比较图

,教育人的诗句或名言警句,激励人在逆境中脱颖而出的话

你真得懂Javascript中的==等于运算符吗?

相关文章:

你感兴趣的文章:

标签云: