9.12 The SameValue Algorithm链接描述
9.12 The SameValue Algorithm
The internal comparison abstract operation SameValue(x, y), where x and y are ECMAScript language values, produces true or false. Such a comparison is performed as follows:
1.If Type(x) is different from Type(y), return false.
2.If Type(x) is Undefined, return true.
3.If Type(x) is Null, return true.
4.If Type(x) is Number, then.
a.If x is NaN and y is NaN, return true.
b.If x is +0 and y is -0, return false.
c.If x is -0 and y is +0, return false.
d.If x is the same Number value as y, return true.
e.Return false.
5.If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions); otherwise, return false.
6.If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
7.Return true if x and y refer to the same object. Otherwise, return false.
function SameValue (a,b){
// Number.isNaN=Number.isNaN||function (a){return typeof a==='number'&&isNaN(a);};
if (typeof a !== typeof b) {
//类型不同
return false;
} else if (typeof a === 'undefined') {
//类型相同都为undfined
return true;
} else if (typeof a === 'object'){
//object有三种Array,{},null
if (a === null && b === null) {
//同为null
return true;
} else if (Array.isArray(a) && Array.isArray(b)){
//同为array
var alength = a.length,
blength = b.length;
if (alength === blength){
for (var i = 0; i < alength; i++) {
if (!SameValue(a[i], b[i])) {
return false;
}
}
return true;
} else {
return false;
}
}else if (a !== null && !Array.isArray(a) && b !==null && !Array.isArray(b)){
//处理都为object时
return true;
}else{
//虽都为object,但不同null或array或{}
return false;
}
} else if (typeof a === 'number') {
//number有三种NaN,0,+-infinity不考虑
if (isNaN(a) && isNaN(b)){
return true;
}else if (a === b){
return true;
}else{
return false;
}
}else if (a.toString() === b.toString()){
//其他情况剩余function
return true;
}else{
return false;
}
}
暂时未实现第4条的b,c..以及{}相等的解析未做。。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。