[关闭]
@JunQiu 2018-09-18T12:53:03.000000Z 字数 2657 阅读 1599

Js_valueOf()/toString()/ToPrimitive(),装箱/拆箱(隐式/显示),类型转换

language_js summary_2018/07

1、日常工作

2、技术学习
  1. The internal operation ToPrimitive() has the following signature:
  2. ToPrimitive(input, PreferredType?)
  3. The optional parameter PreferredType is either Number or String. It only expresses a preference, the result can always be any primitive value. If PreferredType is Number, the following steps are performed to convert a value input 9.1):
  4. 规则如下:
  5. If input is primitive, return it as is.
  6. Otherwise, input is an object. Call obj.valueOf(). If the result is primitive, return it.
  7. Otherwise, call obj.toString(). If the result is a primitive, return it.
  8. Otherwise, throw a TypeError.
  9. If PreferredType is String, steps 2 and 3 are swapped. If PreferredType is missing then it is set to String for instances of Date and to Number for all other values.


  1. #### Number转换规则
  2. 1 ToNumber() converts primitives to number
  3. // 数值:转换后还是原来的值
  4. Number(324) // 324
  5. // 字符串:如果可以被解析为数值,则转换为相应的数值
  6. Number('324') // 324
  7. // 字符串:如果不可以被解析为数值,返回 NaN
  8. Number('324abc') // NaN
  9. // 空字符串转为0
  10. Number('') // 0
  11. // 布尔值:true 转成 1,false 转成 0
  12. Number(true) // 1
  13. Number(false) // 0
  14. // undefined:转成 NaN
  15. Number(undefined) // NaN
  16. // null:转成0
  17. Number(null) // 0
  18. Tips:Number函数将字符串转为数值,要比parseInt函数严格很多。基本上,只要有一个字符无法转成数值,整个字符串就会被转为NaN
  19. parseInt('42 cats') // 42
  20. Number('42 cats') // NaN
  21. 2An object obj is converted to a number by calling ToPrimitive(obj, Number) and then applying ToNumber() to the (primitive) result.
  22. ##### String转换规则
  23. 1converts primitives
  24. 数值:转为相应的字符串。
  25. 字符串:转换后还是原来的值。
  26. 布尔值:true转为字符串"true"false转为字符串"false"
  27. undefined:转为字符串"undefined"
  28. null:转为字符串"null"
  29. 2object
  30. String方法的参数如果是对象,返回一个类型字符串;如果是数组,返回该数组的字符串形式。
  31. String({a: 1}) // "[object Object]"
  32. String([1, 2, 3]) // "1,2,3"
  33. Tips:String方法背后的转换规则,与Number方法基本相同,只是互换了valueOf方法和toString方法的执行顺序。
  34. ##### blooean转换规则
  35. ->除了以下五个值的转换结果为false,其他的值全部为true
  36. undefined
  37. null
  38. -0或+0
  39. NaN
  40. ''(空字符串)
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注