显式类型转换

Number

  1. var a = "123";
  2. console.log(Number(a)); // 123
  3. Number(true); // 1
  4. Number('true') // NaN
  5. Number(null); // 0
  6. Number(undefined); // NaN
  7. Number('1aa'); // NaN
  8. Number('3.1'); // 3.1

parseInt

看不到数字,一律返回NaN

  1. parseInt('123'); // 123
  2. parseInt(true); // NaN
  3. parseInt(null); // NaN
  4. parseInt(undefined); // NaN
  5. parseInt(NaN); // NaN
  6. parseInt('1a'); // 1
  7. parseInt('3.13'); // 3
  8. parseInt('3.13a'); // 3
  9. parseInt('a1234'); // NaN

parseInt(‘10’, 16)

parseInt(xx, [2, 32])

  1. parseInt('10', 16); // 16
  2. parseInt('b', 16); // 11

parseFloat

  1. parseFloat('123'); // 123
  2. parseFloat(true); // NaN
  3. parseFloat(null); // NaN
  4. parseFloat(undefined); // NaN
  5. parseFloat(NaN); // NaN
  6. parseFloat('1a'); // 1
  7. parseFloat('3.13'); // 3.13
  8. parseFloat('3.13a'); // 3.13
  9. parseFloat('a1234'); // NaN
  10. ('3.1415').toFixed(2); // 3.14

转目标进制

  1. (100).toString(16) // '64'

Boolean

  1. Boolean(null|undefined|NaN|""|0|false);// false

隐式类型转换

  1. var a = '123'; // Number(a) ++
  2. a ++;
  3. console.log(a); // 124
  4. var a = "a" + 1; // "a" + String(1)
  5. console.log(a); // "a1"
  6. 1 > '2'; // false 转为number再比较
  7. // 只有两边都是字符串的时候才会转为ascill进行比较
  8. 1 != '2'; // true 转为number再对比
  9. 1 === '1'; // false 不进行隐式转化
  10. NaN == NaN; // false
  11. 2 > 1 > 3; // false
  12. 2 > 1 == 1; // true
  13. undefined == 0; // false Number(undefined)==>NaN
  14. null == 0;// false
  15. // undefined与null既不大于0,也不小于0,也不等于0
  16. undefined == null; // true
  17. -'abc' +'abc' // NaN

IsNaN

  1. window.isNaN(123); // false;
  2. window.isNaN('123'); // false
  3. window.isNaN('a'); // true
  4. window.isNaN(undefined); // true
  5. window.isNaN(null); // false
  6. // window.isNaN先进行了隐式转换,再去判断是否是NaN
  7. Number.isNaN去除了隐式转换,如果不是数字类型,直接返回false

面试题

  1. typeof(a) && (-true) + (undefined) + '';
1 + 5 * '3' === 16
!!' ' + !!'' - !!false || 'pass';