原始值转化原始值:

  1. console.log(Number(undefined)) // NaN
  2. console.log(Number(null)) //0
  3. console.log(Boolean(undefined)) //false
  4. console.log(Boolean(null)) //false
  5. false值: undefined null 0(+0 -0) '' NaN false
  6. Infinity 数字
  7. Number(Infinity) //Infinity
  8. Boolean(Infinity) //true

对象转化原始值:

  1. 以下情况都为true:
  2. Boolean([])
  3. Boolean({})
  4. Boolean(/d/)
  5. Boolean(new Error())
  6. Boolean(Symbol())
  7. typeof Symbol() //symbol
  8. typeof Date() //string
  9. typeof new Date() // object
  10. var obj = {
  11. toString(){
  12. return 1;
  13. },
  14. valueOf(){
  15. return 2;
  16. }
  17. }
  18. Number(obj) // 2
  19. var obj = {
  20. //toString(){
  21. // return 1;
  22. //},
  23. valueOf(){
  24. return {};
  25. }
  26. }
  27. Number(obj) // NaN
  28. Number()
  29. 1. valueOf() 值是原始值,Number()包装以后返回
  30. 2. 不是原始值 -> toString()(注意调用的哪个toString) -> 是原始值, Number包装后返回
  31. 3. toString() 返回不是原始值 -> 报错
  32. Number([1,2]) //NaN Array.prototype.toString.call([1,2]) // 1,2
  33. Number([10]) //10
  34. Number({}) //NaN
  35. Number('123abc') //NaN
  36. parseInt('123abc') //123 将字符串转为整数数字
  37. parseFloat()
  38. String()
  39. 1. toString() -> 值是原始值,String()包装以后返回
  40. 2. 不是原始值 -> valueOf() -> 是原始值,String()包装以后返回
  41. 3. valueOf()返回不是原始值 -> 报错
  42. String([1,2]) // 1,2
  43. '' + [1,2] //1,2
  44. String({}) // [object Object]
  45. '' + {} // [object Object]
  46. typeof Number() // string
  47. typeof New Number() // object
  48. typeof Boolean() // string
  49. typeof New Boolean() // object
  50. typeof String() // string
  51. typeof New String() // object

隐式类型转换

  1. 涉及布尔转化
  2. if()
  3. for(; ;)
  4. switch
  5. while
  6. &&
  7. ||
  8. !
  9. !!
  10. ? :
  11. 转化为数字
  12. Number()
  13. + - * / % +a
  14. == !== >= <= < >
  15. console.log(undefined == null) // true
  16. console.log(undefined == false)// false
  17. console.log(undefined == true) // false
  18. console.log(NaN == NaN) // false
  19. // 全部转为number
  20. console.log(1 == true); // boolean值转为数字
  21. console.log('1' == true);
  22. console.log('1' == 1); // 字符串转化为数字 Number()
  23. console.log([1] == 1); //true
  24. console.log([1] == true); //true
  25. console.log([] == false); //true
  26. Number([1,2]) // 1,2 ->NaN
  27. Number([]) //0
  28. //false: undefined null 0 NaN '' false
  29. console.log([] == ![]) // [] -> 0 ![] ->false []为true
  30. console.log({} == !{}) // {} -> true !{} -> false