JS基本数据类型-判断方法

108 阅读1分钟

一、数据类型

1.基本类型

  • String: 任意字符串
  • Number: 任意的数字
  • boolean: true/false
  • undefined: undefined
  • null: null

2.对象(引用)类型

  • Object: 任意对象
  • Function:一种特别的对象(可以执行)
  • Array:一种特别的对象(数值下标,内部数据是有序的)

二、判断方法

1.typeof

  • 只能判断: 'undefined'/'number'/'string'/'boolean'/'function'
let word
console.log(typeof word === 'undefined') //true

let num = 10
console.log(typeof num === 'number')  //true

typeof 变量 返回的是变量类型对应的字符串,例如 typeof num 返回的是'number'

2.instanceof

  • 判断对象的具体类型
let newObj={
  newArr:[1,2,3],
  newFn:function(){console.log(123)}
}
console.log(newObj instanceof Object) //true
console.log(newObj instanceof Array) //false

console.log(newObj.newArr instanceof Object) //true
console.log(newObj.newArr instanceof Array) //true

console.log(newObj.newFn instanceof Object) //true
console.log(newObj.newFn instanceof Array) //false
console.log(newObj.newFn instanceof Function) //true

变量 instanceof Object/Array/Function 判断变量属于具体哪一种类型,返回true/false

  • instanceof 可以检测对象是不是某个类创建,是否是某个类的实例对象

3.===

  • 可以判断undefined/null,因为它们的值只有一个
let word = null
console.log(word === null)    //true 
console.log(word === 'null')  //false

let words
console.log(words === undefined)   //true
console.log(words === 'undefined') //false

总结

本文主要介绍js基本数据类型,以及判断变量类型的基本方法,基本方法实际使用中比较频繁,当然还有更多判断方法