1. JS数据类型
基本数据类型:String、Number、boolean、null、undefined、symbol(es6新增的)
引用数据类型:object(包含 Function、Array、Date、RegExp、Error等)
2. 判断数据类型的方法
(1)typeof 通常用来判断基本数据类型
,它返回表示数据类型的字符串(返回结果只能包括number,boolean,string,function,undefined,object)
注意
:使用typeof来判断null和引用类型 返回的结果都是 'object'
typeof 1 //number
typeof 'a' //string
typeof true //boolean
typeof undefined //undefined
typeof null //object
typeof {} //object
typeof [1,2,3] //object
function Fn(){} // 函数类型
typeof new Fn() //object
typeof new Array() //object
(2)instanceof 用来判断两个对象是否属于实例关系,而不能判断一个对象实例具体属于哪种类型,例:a instanceof A
根据instanceof的定义:判断参照对象(大写字母A)的prototype属性所指向的对象是否在被行测对象a的原型链上
function A(name,age){
this.name = name;
this.age = age;
}
a = new A('哈哈',18);
console.log(a instanceof A) //true
obj = new Object()//创建一个空对象obj
//或者通过字面量来创建:
obj = {}
console.log(obj instanceof Object); // true
arr = new Array() //创建一个空数组arr 或arr = []
console.log(arr instanceof Array ); // true
date = new Date()
console.log(date instanceof Date ); // true
// 注意:instanceof后面一定要是对象类型,instanceof前面相当于它的实例对象,
// 后面的对象类型大小写不能写错
注
:这种方式的弊端:对于number,string,boolean这三种基本数据类型,只有通过构造函数定义:比如:let num = new Number(1)
这样定义才能检测出来,let num = 1
; 这样定义是检测不出来的
(3)constructor 通过原型对象的属性指向构造函数
let num = 2222;
let date = new Date();
let str = "hhhh";
let reg = new RegExp();
let bool = true;
let fn = function () {
console.log('ssss');
};
let udf = undefined;
let nul = null;
let array = [1, 2, 3];
console.log(num.constructor); // [Function: Number]
console.log(date.constructor); // [Function: Date]
console.log(str.constructor); // [Function: String]
console.log(bool.constructor); // [Function: Boolean]
console.log(fn.constructor); // [Function: Function]
console.log(reg.constructor); // [Function: RegExp]
console.log(array.constructor); // [Function: Array]
注
:可以检测出除了undefined
和null
的9种类型(因为它两没有原生构造函数)
(4)Object.prototype.toString(…) 所有typeof返回值为"object"的对象,都包含一个内部属性[[Class]],可以把他看作一个内部的分类,而非传统意义上面向对象的类,这个属性无法直接访问,一般通过Object.prototype.toString(…)来查看。并且对于基本数据类类型null,undefined这样没有原生构造函数,内部的[[Class]]属性值仍然是Null和Undefined
console.log(toString.call(123)); //[object Number]
console.log(toString.call('123')); //[object String]
console.log(toString.call(undefined)); //[object Undefined]
console.log(toString.call(true)); //[object Boolean]
console.log(toString.call({})); //[object Object]
console.log(toString.call([])); //[object Array]
console.log(toString.call(function(){})); //[object Function]