注意: js中数据类型有7种(number, boolean, string, null, undefined, object, Symbol(es6新增))
原始数据类型: number, string, boolean
引用数据类型(合成类型): object
特殊类型: null ,undefined
一 最常用方法,基本类型 typeof
typeof 运算符的最终结果有6种
"number" -> typeof 123 ; typeof NaN
"string" -> typeof "123"
"boolean" -> typeof true
"function" -> function f() {}; typeof f
"object" -> typeof {}; typeof [];typeof new Date(); typeof null; typeof window //缺点: 不能细分对象,数组,时间对象
"undefined" -> typeof undefined; typeof 未定义变量
二 判断对象类型 instanceof
判断是否为某个构造函数或者类的实例
([2]) instanceof Array -> true
(new Date()) instanceof Date -> true
(function(){}) instanceof Function -> true
({}) instanceof Object -> true
null,undefined 使用该运算法的时候,返回值永远是 false
三 判断对象类型 constructor
constructor
属性的作用是,可以得知某个实例对象,到底是哪一个构造函数产生的。
因为js规定:P.prototype.constructor === P
([2]).constructor === Array -> true
(function(){}).constructor === Function -> true
({}).constructor === Object -> true
instanceof 和 constructor 两者区别:
function A(){};
function B(){}; A.prototype = new B(); //A继承自B var aobj = new A(); console.log(aobj.constructor === B) -> true console.log(aobj.constructor === A) -> false console.log(aobj instanceof A) -> true console.log(aobj instanceof B) -> trueclass A{};
class B{}; A.prototype = new B(); //A继承自B var obj = new A(); console.log(obj.constructor === B) -> false console.log(obj.constructor === A) -> true console.log(obj instanceof A) -> true console.log(obj instanceof B) -> false四. 通用方法
Object.prototype.toString() 默认返回类型字符串。所有的值都继承该方法。
但是数组、字符串、函数、Date 对象都又定义了属于自己的toString方法,覆盖了继承的Object.prototype的toString()方法。
所以为了可以判断所有的类型,统一使用Object.prototype.toString.call(value),来判断数据类型。
call方法是用于改变this的指向,value就是方法运行时的实例对象,如果value是原始值,会自动将其转为对应的包装对象。
- 数值:返回
[object Number]
。 - 字符串:返回
[object String]
。 - 布尔值:返回
[object Boolean]
。 - undefined:返回
[object Undefined]
。 - null:返回
[object Null]
。 - 数组:返回
[object Array]
。 - arguments 对象:返回
[object Arguments]
。 - 函数:返回
[object Function]
。 - Error 对象:返回
[object Error]
。 - Date 对象:返回
[object Date]
。 - RegExp 对象:返回
[object RegExp]
。 - 其他对象:返回
[object Object]
。
*************判断一个变量是否是对象的方法*************
function isObject(value) { return value === Object(value)}// 注意,原始类型的值通过Object()函数之后,会变成对应的包装对象;// 对象(数组,对象,函数)等于本身
****************************************************