05.包装类.html 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <script>
  9. /*
  10. 基本数据类型
  11. String Number Boolean Null Undefined
  12. 引用数据类型
  13. Object
  14. 在JS中为我们提供了三个包装类,通过这三个包装类,可以将基本数据类型的数据转换为对象
  15. String()
  16. -可以将基本数据类型字符串转换为String对象
  17. Number()
  18. -可以将基本数据类型的数字转换为Number对象
  19. Boolean()
  20. -可以将基本数据类型的布尔值转换为Boolean对象
  21. 但是注意:我们在实际应用中不会使用基本数据类型的对象,
  22. 如果使用基本数据类型的对象,在做一些比较时可能会带来一些不可预期的结果
  23. */
  24. //创建一个Number类型的对象
  25. var num = new Number(3);
  26. // console.log(num);
  27. // console.log(typeof num);
  28. var str =new String("hello");
  29. // console.log(str);
  30. // console.log(typeof str);
  31. var bool = new Boolean(true);
  32. // console.log(bool);
  33. // console.log(typeof bool);
  34. //向num中添加一个属性
  35. // var num = new Number(3);
  36. // num.hello = "abc";
  37. // console.log(num.hello);//输出结果为abc
  38. // var a = 3;
  39. // a.hello="abc";
  40. // console.log(a.hello);//输出结果为undefined
  41. // var num = new Number(3);
  42. // var num2 = new Number(3);
  43. // console.log(num == num2);//false
  44. var bool = new Boolean(true);
  45. var bool2 = true;
  46. // console.log(bool == bool2);//true
  47. // console.log(bool === bool2);//false
  48. var b = new Boolean(false);
  49. // if(b){
  50. // alert("我运行了~~");
  51. // }
  52. /*
  53. 方法和属性只能添加给对象,不能添加给基本数据类型
  54. 当我们对一些基本数据类型的值去调用属性和方法时,
  55. 浏览器会临时使用包装类将其转换为对象,然后再调用对象的属性和方法
  56. 调用完以后,再将其转换为基本数据类型
  57. */
  58. // var s = 123;
  59. // s = s.toString();
  60. // console.log(s);
  61. // console.log(typeof s);
  62. var s = 123;
  63. s = s.toString();
  64. s.hello = "你好";
  65. console.log(s.hello);
  66. </script>
  67. </head>
  68. <body>
  69. </body>
  70. </html>