JavaScript中,==与===操作符均可用于判断两个值是否相等;不同之处在于,如果进行判断的两个值类型不一致,===操作符会直接返回false,而==操作符则会在类型转换后再进行判断。详细的判断规则如下:
==操作符会将值进行类型转换后再进行比较,其类型转换遵循以下原则:优先转换成number后进行比较,Date对象则优先转换成string后进行比较。具体判断规则如下:
console.log("3" === 3);//false
console.log(NaN === NaN);//false
var a = {x:1, y:2};
var b = {x:1, y:2};
var c = a;
console.log(a === b);//false
console.log(a === c);//true
console.log(0 === -0);//true
console.log("3" == 3);//true
console.log(null == undefined);//true
console.log(true == 1);//true
console.log(true == 9);//false
console.log([9] == 9);//true
console.log([9] == "9");//true
var d = new Date();
var s = d.toString();
var n = d.valueOf();
console.log(d == s);//true
console.log(d == n);//false