显式类型转换
Number
var a = "123";
console.log(Number(a)); // 123
Number(true); // 1
Number('true') // NaN
Number(null); // 0
Number(undefined); // NaN
Number('1aa'); // NaN
Number('3.1'); // 3.1
parseInt
看不到数字,一律返回NaN
parseInt('123'); // 123
parseInt(true); // NaN
parseInt(null); // NaN
parseInt(undefined); // NaN
parseInt(NaN); // NaN
parseInt('1a'); // 1
parseInt('3.13'); // 3
parseInt('3.13a'); // 3
parseInt('a1234'); // NaN
parseInt(‘10’, 16)
parseInt(xx, [2, 32])
parseInt('10', 16); // 16
parseInt('b', 16); // 11
parseFloat
parseFloat('123'); // 123
parseFloat(true); // NaN
parseFloat(null); // NaN
parseFloat(undefined); // NaN
parseFloat(NaN); // NaN
parseFloat('1a'); // 1
parseFloat('3.13'); // 3.13
parseFloat('3.13a'); // 3.13
parseFloat('a1234'); // NaN
('3.1415').toFixed(2); // 3.14
转目标进制
(100).toString(16) // '64'
Boolean
Boolean(null|undefined|NaN|""|0|false);// false
隐式类型转换
var a = '123'; // Number(a) ++
a ++;
console.log(a); // 124
var a = "a" + 1; // "a" + String(1)
console.log(a); // "a1"
1 > '2'; // false 转为number再比较
// 只有两边都是字符串的时候才会转为ascill进行比较
1 != '2'; // true 转为number再对比
1 === '1'; // false 不进行隐式转化
NaN == NaN; // false
2 > 1 > 3; // false
2 > 1 == 1; // true
undefined == 0; // false Number(undefined)==>NaN
null == 0;// false
// undefined与null既不大于0,也不小于0,也不等于0
undefined == null; // true
-'abc' +'abc' // NaN
IsNaN
window.isNaN(123); // false;
window.isNaN('123'); // false
window.isNaN('a'); // true
window.isNaN(undefined); // true
window.isNaN(null); // false
// window.isNaN先进行了隐式转换,再去判断是否是NaN
Number.isNaN去除了隐式转换,如果不是数字类型,直接返回false
面试题
typeof(a) && (-true) + (undefined) + '';
1 + 5 * '3' === 16
!!' ' + !!'' - !!false || 'pass';