JS高级(1)—— 关于 数据类型

一、分类(2大类)

1. 基本(值)类型
  • Number: 任意数值
  • String: 任意文本
  • Boolean: true / false
  • undefined: undefined
  • null: null

2. 对象(引用)类型
  • Object: 任意对象
var obj ={}
  • Function: 特别的对象类型(可执行)
function test(){
    var a = 3;
  }
  • Array: 特别的对象类型(根据数值下标操作,内部数据有序)
var arr = [3,'abc']
console.log(arr[1]); //abc

二、判断
  • typeof:返回的是数据类型的字符串表达形式
    • 可以区别:数值, 字符串, 布尔值, undefined, function
    • 不能区别:null与对象, 一般对象与数组
  • ===
    • 可以判断:undefined 和 null
//1. 基本类型
// typeof: 返回的是数据类型的字符串表达形式
var a
console.log(a, typeof a, typeof a==='undefined',a===undefined) // undefined 'undefined' true true
console.log(undefined==='undefined'); // false

a = 3
console.log(typeof a === 'number')//true
a = 'atguigu'
console.log(typeof a === 'string')//true
a = true
console.log(typeof a === 'boolean')//true

a = null
console.log(a===null) // true
console.log(typeof a) // 'object'  故:不能区别: null与对象

在这里插入图片描述

  • instanceof
    • 专门用来判断对象数据的类型: Object,Array与Function
//2. 对象类型
  var b1 = {
    b2: [2, 'abc', console.log],
    b3: function () {
      console.log('b3')      
    }
  }
  
//b1 instanceof Object  意思是:判断 b1 是不是 Object 的实例
console.log(b1 instanceof Object, b1 instanceof Array, typeof b1) // true false 'object'
console.log(b1.b2 instanceof Array, b1.b2 instanceof Object, typeof b1.b2) // true true 'object'
console.log(b1.b3 instanceof Function, b1.b3 instanceof Object, typeof b1.b3) // true true 'function'


//typeof 可以区别 function ,不能区别 object 和 数组
console.log(typeof b1.b2[2]) // 'function'

console.log(typeof b1.b2, '-------') // 'object'

console.log(typeof b1.b3==='function') // true

console.log(typeof b1.b2[2]==='function') // true

b1.b2[2](3);  //3
b1.b3();  //b3

在这里插入图片描述

var b1 = {
    b2: [2, 'abc', console.log],
    b3: function () {
      console.log('b3')  //b3
      return function () {
        return 'xxx'
      }
    }
  }

b1.b2[2](3);  //3
b1.b3();  //b3
console.log(b1.b3()());  //xxx

在这里插入图片描述

三、undefined 与 null 的区别
  • undefined代表没有赋值
  • null代表赋值了, 只是值为null
var a
console.log(a)  // undefined
a = null
console.log(a) // null
四、什么时候给变量赋值为 null
  1. 初始赋值,表明将要赋值为对象,var a = null ,a将指向一个对象,但对象此时还没有确定。
  2. 结束前,让对象成为垃圾对象(被垃圾回收器回收) ,a = null 。
//起始
var b = null  // 初始赋值为null, 表明将要赋值为对象
//确定对象就赋值
b = ['atguigu', 12]
//最后
b = null // 让b指向的对象成为垃圾对象(被垃圾回收器回收)
五、严格区别变量类型与数据类型

js的变量本身是没有类型的, 变量的类型实际上是变量内存中数据的类型。

  • 变量类型(变量内存值的类型):
    • 基本类型: 保存基本类型数据
    • 引用类型: 保存对象地址值
  • 数据对象
    • 基本类型
    • 对象类型
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值