javascript object comparison
Comparison symbols:==,!=,===,!==,>=,<=,>,< ;
== Always try to compare their straightness, and if the types are different, always try to convert.
=== Compare for identity, compare without conversion
== If it is a basic type (string, number, boolean), compare their values,
var a = "123";
var b = 123;
(a==b) = true;
(a===b) = false;
If it is object, array , function type, compare their references. It is true only when their references are equal.
function Point(x,y){
this.x = x;
this.y = y ;
};
Point.prototype.toString = function(){
alert("in toString");
return "x=" this.x " y=" this.y;
};
Point.prototype.valueOf = function(){
alert("in valueOf");
return this.x this.y;
};
var pa = new Point(1,1);
var pb = new Point(1,1);
var pc = pa;
then: pa!=pb ;
pa!==pb;
pa==pc;
pa===pc;
var arr1 = [1,2,3];
var arr2 = [1,2,3];
arr1!=arr2, arr1!==arr2
I have to say 0, false, null, undefined
var t1 = 0;
var t2 = false;
var t3 = null;
var t4;
then: t1==t2;t1!==t2;
t1!=t3; t1!==t3;
t1!=t4; t1!==t4;
t2!=t3; t2!==t3;
t2!=t4; t2!==t4;
t3==t4; t3!==t4;
If an object is compared with a basic type, first call the object's valueOf, and then call the object's toString to compare with the basic type
If it is compared with boolean, first convert true to 1 ,false is converted to 0 and then compared.
var pa = new Point(1,1);
alert(pa==2); will output "in valueOf" and then "true";
If Point.prototype is blocked .valueOf then outputs "in toString" and then "false";
var pa = new Point(1,0);
then pa==true;
Relational Operator>= ,<=,>,<
If both sides are numbers or can be converted to numbers, numbers are compared.
If both sides are strings, or can be converted to strings, compare strings.
If one side can be converted to string and the other side can be converted to number, then try to convert string to number and compare. If string cannot be converted to number, it will be NaN and false will be returned.
If there is an object participating in the comparison, Then it always tries to convert object to number or string and then compare.
Here is an interesting example:
function Point(x,y){
this.x = x;
this.y = y;
};
Point.prototype.toString = function(){
alert("in toString");
return "x=" this.x " y=" this.y;
};
Point.prototype.valueOf = function(){
alert("in valueOf");
return this.x this.y;
};
var pa = new Point(1,1);
var pb = new Point(1,1);
then(pa==pb)==false;
(pa> pb)==false;
(pa
(pa>=pb) == true;
(pa<=pb ) == true;