JavaScript进阶篇(一)——数据类型

数据类型

一、分类

1、基本(值)数据类型
  • String:任意字符串
  • Number:任意数字
  • Boolean:true/false
  • Undefined: undefined
  • null:null
2、对象(引用)类型
  • Object:任意对象,Function和Array本质上也是对象,是特殊的对象
  • Function:一种特别的对象(可以执行)
  • Array:一种特别的对象(数值下标访问,内部数据是有序的)

二 、如何判断数据类型

  • typeof:返回数据类型的字符串表达;可以判断undefined、数值、字符串、布尔值、function;
    不能判断null与object、object与array
 	  let a
      console.log(a, typeof a)  // undefined "undefined"
      console.log(a === undefined, typeof a === 'undefined')  // true true
      a = 3
      console.log(typeof a === 'number')  // true
      a = 'hello'
      console.log(typeof a === 'string')  // true
      a = true
      console.log(typeof a === 'boolean') // true
      a = null
      console.log(typeof a, a === null)  // object true
  • instanceof:返回布尔值;判断对象具体类型
		let b = {
    
    
		        b1: [1, 2, console.log],
		        b2: function () {
    
    
		          console.log('hello')
		        }
		      }
      console.log(b instanceof Object)  // true
      console.log(b.b1 instanceof Array, b.b1 instanceof Object)   // true true
      console.log(b.b2 instanceof Function, b.b2 instanceof Object)  // true true
      console.log(typeof b.b2 === 'function')  // true
  • ===:可以判断undefined、null

undefined与null区别

undefined: 定义了但未赋值;
null: 定义了并且已经赋值,赋值为null

	  let c
      console.log(c)   // undefined
      c = null
      console.log(c)  // null

什么时候给变量赋值为null

  • 初始赋值为null,表明将要赋值为对象
  • 结束前,让对象成为垃圾对象(被垃圾回收器回收)

猜你喜欢

转载自blog.csdn.net/weixin_42164004/article/details/109073828