隐式转换之字符串和数值比较

1.字符串和数值比较,这种数值字符串会隐式转换为数值类型然后比较

var aa='6';
console.log(aa<8); // 输出为true 

2.如果aa带有其他字符

var aa='6元';
console.log(aa<8); // 输出为false,不报错

3.如果给aa转换成数值类型为NaN

var aa='6元';
console.log(Number(aa)); // 输出为NaN 

4.如果数值和NaN比较

var aa='6元';
console.log(aa<NaN); // 输出为false,不报错

5.带数值字符和NaN、null、undefined比较

var aa='6个';
console.log(aa>NaN); // 输出为false 
console.log(aa>undefined); // 输出为false 
console.log(aa>null); // 输出为true

6.数值和NaN、null、undefined比较

var aa='6';
console.log(aa>NaN); // 输出为false 
console.log(aa>undefined); // 输出为false 
console.log(aa>null); // 输出为true 

总结:可见在字符串和数值字符串比较的时候,数值字符串会尝试隐式转换为数值类型然后在进行比较,当转为NaN的时候,任何数和NaN以及undefined比较都为false,但是数值和null,都为true

猜你喜欢

转载自www.cnblogs.com/bonly-ge/p/9261653.html