码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-06-12 10:11:08      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

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; // false
false == undefined; // false
false == NaN; // false
false == 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; // false
0 == undefined; // false
0 == NaN; // false
0 == []; // 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; // false
var c = undefined;
var d = Object( c ); // same as `Object()`
c == d; // false
var e = NaN;
var f = Object( e ); // same as `new Number( e )`
e == f; // false


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

ES5规范中的解释:

Comparing: objects to nonobjects
If an object/function/array is compared to a simple scalar primitive
(string, number, or boolean), the ES5 spec says in clauses
11.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 undefineds
Another example of implicit coercion can be seen with == loose
equality between null and undefined values. Yet again quoting the
ES5 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 boolean
1. If Type(x) is Boolean, return the result of the comparison
ToNumber(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 of
the comparison x == ToNumber(y).
2. If Type(x) is String and Type(y) is Number, return the result of
the comparison ToNumber(x) == y.


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

http://dorey.github.io/JavaScript-Equality-Table/

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

标签:

原文地址:http://blog.csdn.net/kittyjie/article/details/46467355

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!