本篇文章给大家带来的内容是关于JavaScript中比较运算符隐式类型转换的介绍(附示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
相信大家在代码中经常看见 '==' 和 '===',但大家真的弄懂了比较运算符和其中的隐式转换嘛? 今天就重新认识下比较运算符。
全等运算符 ===
说明: 严格匹配,不会类型转换,必须要数据类型和值完全一致
1 2 3 4 5 6 7 8 9 10 11 12 | 先判断类型,如果类型不是同一类型的话直接为false;
1 对于基本数据类型(值类型): Number,String,Boolean,Null和Undefined:两边的值要一致,才相等
console.log(null === null)
console.log(undefined === undefined)
注意: NaN: 不会等于任何数,包括它自己
console.log(NaN === NaN)
2 对于复杂数据类型(引用类型): Object,Array,Function等:两边的引用地址如果一致的话,是相等的
arr1 = [1,2,3];
arr2 = arr1;
console.log(arr1 === arr2)
|
Salin selepas log masuk
相等运算符 ==
非严格匹配: 会类型转换,但是有前提条件一共有五种情况
(接下来的代码以 x == y 为示例)
x和y都是null或undefined:
规则: 没有隐式类型转换,无条件返回true
1 2 3 | console.log ( null == undefined );
console.log ( null == null );
console.log ( undefined == undefined );
|
Salin selepas log masuk
x或y是NaN : NaN与任何数字都不等
规则:没有隐式类型转换,无条件返回false
1 | console.log ( NaN == NaN );
|
Salin selepas log masuk
x和y都是string,boolean,number
规则:有隐式类型转换,会将不是number类型的数据转成number
1 2 3 4 5 | console.log ( 1 == true );
console.log ( 1 == "true" );
console.log ( 1 == ! "true" );
console.log ( 0 == ! "true" );
console.log(true == 'true' )
|
Salin selepas log masuk
x或y是复杂数据类型 : 会先获取复杂数据类型的原始值之后再左比较
复杂数据类型的原始值: 先调用valueOf方法,然后调用toString方法
valueOf:一般默认返回自身
数组的toString:默认会调用join方法拼接每个元素并且返回拼接后的字符串
1 2 3 4 5 6 7 8 | console.log ( [].toString () );
console.log ( {}.toString () );
注意: 空数组的toString()方法会得到空字符串,
而空对象的toString()方法会得到字符串[object Object] (注意第一个小写o,第二个大写O哟)
console.log ( [ 1, 2, 3 ].valueOf().toString());
console.log ( [ 1, 2, 3 ] == "1,2,3" );
console.log({} == '[object Object]' );
|
Salin selepas log masuk
x和y都是复杂数据类型 :
规则只比较地址,如果地址一致则返回true,否则返回false
1 2 3 4 5 6 7 8 9 | var arr1 = [10,20,30];
var arr2 = [10,20,30];
var arr3 = arr1;
console.log ( arr1 == arr2 );
console.log ( arr3 == arr1 );
console.log ( [] == [] );
console.log ( {} == {} );
|
Salin selepas log masuk
经典面试题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 注意:八种情况转boolean得到false: 0 -0 NaN undefined null '' false document.all()
console.log([] == 0);
console.log(![] == 0);
console.log([] == []);
console.log([] == ![]);
onsole.log({} == {});
console.log({} == !{});
|
Salin selepas log masuk
变态面试题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | var a = ???
if (a == 1 && a == 2 && a == 3 ){
console.log(1)
}
var a = {
i : 0,
valueOf: function ( ) {
return ++a.i;
}
}
if (a == 1 && a == 2 && a == 3){
console.log ( "1" );
}
|
Salin selepas log masuk
本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的JavaScript视频教程栏目!
Atas ialah kandungan terperinci JavaScript中比较运算符隐式类型转换的介绍(附示例). Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!