相等运算符用来比较两个值是否相等,如果相等会返回true,否则返回false
1.使用 == 来做相等运算
当使用==来比较两个值时,如果值的类型不同,则会自动进行类型转换,将其转换为相同的类型,然后在比较
var a = 10;console.log(a == 4); //falseconsole.log("1" == 1); //true 将字符串“1”转为数字1console.log(true == "1"); //true 将true和“1”都转为数字1console.log(null == 0); //false null 并没有转为0 所以只是大部分是情况下都是转为数字,这是特殊情况/** undefined 衍生自 null* 所以这两个值做相等判断时,会返回true*/console.log(undefined == null);//true/** NaN不和任何值相等,包括他本身*/console.log(NaN == null); //falseconsole.log(NaN == NaN); //false//判断b的值是否是NaNvar b = NaN;//console.log(b == NaN);//false/** 可以通过isNaN()函数来判断一个值是否是NaN* 如果该值是NaN则返回true,否则返回false*/console.log(isNaN(b));//true
2.使用 != 来做不相等运算
不相等也会对变量进行自动的类型转换,如果转换后相等它也会返回false
console.log(10 != 5); //trueconsole.log(10 != 10); //falseconsole.log("abcd" != "abcd"); //falseconsole.log("1" != 1);//false
3.===全等(类型不一样直接返回false)
用来判断两个值是否全等,它和相等类似,不同的是它不会做自动的类型转换,如果两个值的类型不同,直接返回false
console.log("123" === 123);//falseconsole.log(null === undefined);//false
4.!==不全等
用来判断两个值是否不全等,和不等类似,不同的是它不会做自动的类型转换如果两个值的类型不同,直接返回true
console.log(1 !="1"); //falseconsole.log(1 !== "1"); //true
