JavaScript的数据类型与判断数据类型

98 阅读1分钟

1. JavaScript的数据类型

javascript数据类型有八种,共分为原始数据类型和引用数据类型两大类

原始数据类型
  1.String
  2.Number
  3.Boolean
  4.Null
  5.Undefined
  6.Symbol
  7.Bigint

引用数据类型
  1.Object

2. JavaScript判断数据类型

2.1 typeof

typeof判断的是变量存储的值的类型,输出的是类型的字符串形式,js变量没有类型 

typeof 不能判断 NullObject ,因为都会输出 "object"
typeof 不能判断 ObjectArray ,因为都会输出 "object"
typeof 能够判断 NullUndefined , 前者输出 "object",后者输出 "undefined"

2.1 instanceof

instanceof 判断对象的的具体类型,基本数据必须是 New 出来的 才能判断
(字符串,数值,布尔,大整数,symbol),引用数据(Object,Number,Functioninstanceof 用于检测构造函数的 `prototype` 属性是否出现在某个实例对象的原型链上
var simpleStr = "This is a simple string";
var myString  = new String();
var newStr    = new String("String created with constructor");
var myDate    = new Date();
var myObj     = {};
var myNonObj  = Object.create(null);

simpleStr instanceof String; // 返回 false,非对象实例,因此返回 false
myString  instanceof String; // 返回 true
newStr    instanceof String; // 返回 true
myString  instanceof Object; // 返回 true

myObj instanceof Object;    // 返回 true,尽管原型没有定义
({})  instanceof Object;    // 返回 true,同上
myNonObj instanceof Object; // 返回 false,一种创建非 Object 实例的对象的方法

myString instanceof Date; //返回 false

myDate instanceof Date;     // 返回 true
myDate instanceof Object;   // 返回 true
myDate instanceof String;   // 返回 false

2.3 Object.prototype.toString.call()

Object.prototype.toString.call(111)  '[object Number]'
Object.prototype.toString.call('hello')  '[object String]'
Object.prototype.toString.call(null)  '[object Null]'
Object.prototype.toString.call(undefined)  '[object Undefined]'
Object.prototype.toString.call(false)  '[object Boolean]'
Object.prototype.toString.call(Symbol('11'))  '[object Symbol]'
Object.prototype.toString.call(11111111n)  '[object BigInt]'

Object.prototype.toString.call(()=>{})  '[object Function]'
Object.prototype.toString.call([])  '[object Array]'
Object.prototype.toString.call({})  '[object Object]'

2.4 constructor

let a = 123
let b = "123"
let c = true

console.log(a.constructor === Number) // true
console.log(b.constructor === String) // true
console.log(c.constructor === Boolean) // true

// constructor不会顺着[原型链]找,但是指向容易被更改
let arr = []
console.log(arr.constructor === Array) // true
console.log(arr.constructor === Object) // false

let arr = []
Array.prototype.constructor = 'a' // 更改constructor
console.log(arr.constructor === Array) // false