15.js数据类型判断.html 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <!--
  10. JS数据类型:
  11. 基本数据类型:
  12. Null Undefined Number Boolean String
  13. 引用数据类型
  14. Object Array Function
  15. -->
  16. <script>
  17. let obj = {
  18. name: 'Lucy',
  19. age: 10
  20. }
  21. let arr = [1,2,3,4,5,6];
  22. function fn1() {
  23. return "哈哈哈"
  24. }
  25. // 1.typeof
  26. // 能判断出: undefined string number boolean function
  27. // 不能判断出: null object array
  28. // console.log(typeof null); // object
  29. // console.log(typeof undefined); // undefined
  30. // console.log(typeof '1'); // string
  31. // console.log(typeof 3); // number
  32. // console.log(typeof true);// boolean
  33. // console.log(typeof obj); // object
  34. // console.log(typeof arr); // object
  35. // console.log(typeof fn1); // function
  36. // 2.obj(任意值) instanceof Object类型
  37. // console.log(obj instanceof Object); // true
  38. // console.log(arr instanceof Array); // true
  39. // console.log(fn1 instanceof Function); // true
  40. // 3.Object.prototype.toString.call()
  41. // console.log(Object.prototype.toString.call(1));// [Object Number]
  42. // console.log(Object.prototype.toString.call("21"));// [Object String]
  43. // console.log(Object.prototype.toString.call(true));// [Object Boolean]
  44. // console.log(Object.prototype.toString.call(undefined));// [Object Undefined]
  45. // console.log(Object.prototype.toString.call(null));// [Object Null]
  46. // console.log(Object.prototype.toString.call(fn1));// [Object Function]
  47. // console.log(Object.prototype.toString.call(arr));// [Object Array]
  48. // console.log(Object.prototype.toString.call(obj));// [Object Object]
  49. // 4.constructor
  50. // 不判断null和undefined
  51. console.log(false.constructor === Boolean); // true
  52. console.log((1).constructor === Number); // true
  53. console.log('2121'.constructor === String); // true
  54. console.log(obj.constructor === Object); //true
  55. console.log(arr.constructor === Array); //true
  56. console.log(fn1.constructor === Function); //true
  57. // console.log(null.constructor === null); //报错
  58. // console.log(undefined.constructor === undefined); // 报错
  59. </script>
  60. </body>
  61. </html>