JS数据类型入门理解

1. 分类(2大类)


  * 基本(值)类型
    * Number: 任意数值
    * String: 任意文本
    * Boolean: true/false
    * undefined: undefined
    * null: null
  * 对象(引用)类型
    * Object: 任意对象
    * Array: 特别的对象类型(下标/内部数据有序)
    * Function: 特别的对象类型(可执行)


2. 判断


  * typeof:
    * 可以区别: 数值, 字符串, 布尔值, undefined, function
    * 不能区别: null与对象, 一般对象与数组
  * instanceof
    * 专门用来判断对象数据的类型: Object, Array与Function
  * ===
    * 可以判断: undefined和null

// typeof: 返回的是数据类型的字符串表达形式
  //1. 基本类型
  var a
  console.log(a, typeof a, a===undefined,66666666666) // undefined 'undefined' true
  console.log(a==typeof a) // false
  //typeof 返回的字符串,a==typeof a 为false
	
  a = 3
  console.log(typeof a === 'number')
  a = 'atguigu'
  console.log(typeof a === 'string')
  a = true
  console.log(typeof a === 'boolean')
 
  a = null
  console.log(a===null) // true
  console.log(typeof a) // 'object'

  console.log('--------------------------------')
 
  //2. 对象类型
  var b1 = {
    b2: [2, 'abc', console.log],
    b3: function () {
      console.log('b3()')
    }
  }
  console.log(b1 instanceof Object, typeof b1) // true 'object'
  console.log(b1.b2 instanceof Array, typeof b1.b2) // true 'object'
  console.log(b1.b3 instanceof Function, typeof b1.b3) // true 'function'

  console.log(typeof b1.b2[2]) // 'function'
  console.log(b1.b2[2]('abc')) // 'abc' undefined
  
  
  var arr = [];
  console.log(arr instanceof Object);//true

 3.小tips

1. undefined与null的区别?
  * undefined代表没有赋值
  * null代表赋值了, 只是值为null
2. 什么时候给变量赋值为null呢?
  * var a = null //a将指向一个对象, 但对象此时还没有确定
  * a = null //让a指向的对象成为垃圾对象
3. 严格区别变量类型与数据类型?
  * js的变量本身是没有类型的, 变量的类型实际上是变量内存中数据的类型
  * 变量类型:
    * 基本类型: 保存基本类型数据的变量
    * 引用类型: 保存对象地址值的变量
  * 数据对象
    * 基本类型
    * 对象类型

猜你喜欢

转载自blog.csdn.net/m0_43599959/article/details/109502664
今日推荐