文章目录
参考链接:1.https://www.cnblogs.com/amiezhang/p/10325558.html
2.https://www.jianshu.com/p/967d6db70437
一、数据类型
-
null
-
undefined
-
boolean
-
number
-
string
-
引用类型(object、array、function)
-
symbol
二、判断类型有以下4种判断方法
第一种方式: typeof
typeof undefined ---> "undefined"
typeof true | false ---> 'boolean'
typeof 42 ---> 'number'
typeof "42" ---> 'string'
typeof null ---> "object"
typeof { name : '1'} | [] ---> 'object'
typeof {} ---> 'object'
typeof [1,2] ---> 'object'
typeof /\s/ ---> 'object'
typeof Symbol ---> 'symbol'
typeof ()=>{} ---> 'function'
typeif void 0 ---> 'undefined'
可以判断数据类型,它返回表示数据类型的字符串(返回结果只能包括number,boolean,string,function,object,undefined);
可以使用typeof判断变量是否存在(如if(typeof a!=“undefined”){…});
typeof 运算符的问题是无论引用的对象是什么类型 它都返回object
第二种方式: instanceof 但是这种方式只适合判断object类型
返回一个布尔值,由构造类型判断出数据类型
var arr = [] ;
arr instanceof Array ---> true
null instanceof Object ---> false
[function] instanceof Object | Function --> true
第三种方式: Object.prototype.toString.call() 这种方式可以将全部的数据类型检测出来 也是 推荐的方式
因为toString是Object的原型方法, 而 Array Function 等都是Object的实例。都重写了toString 方法。返回的是类型的字符串
Object.prototype.toString.call(null) ---> [object Null]
Object.prototupe.toString.call(undefined) ---> [object Undefined]
Object.prototype.toString.call(123) ---> [object Number]
Object.prototype.toString.call(true) ---> [object Boolean]
Object.prototype.toString.call('123') ---> [object String]
Object.prototype.toString.call({}) ---> [object Object]
Object.prototype.toString.call([]) ---> [object Array]
Object.prototype.toString.call(Math) ---> [object Math]
Object.prototype.toString.call(function(){}) ---> [object Function]
Objdec.prototype.toString.call(new Date) ---> [object Date]
Object.prototype.toString.call(Symbol()) ---> [object Symbol]
第四种方式: constructor 判断对象的构造函。
1. null 是js 原型链的起点,没有构造函数
2. undefined 没有构造函数
3. [].constructor === Array ---> true
4. [string].constructor === String
5. [object].constructor === object
6. [number].constructor === Number
7. [symbol].constructor === Symbol
8. [function].constructor === Function
9. [new Date].constructor === Date
10. [RegExp].constructor === RegExp
三、jQuery判断数据类型
jQuery提供了一系列工具方法,用来判断数据类型,以弥补JavaScript原生的typeof运算符的不足。
以下方法对参数进行判断,返回一个布尔值
。
jQuery.isArray();是否为数组
jQuery.isEmptyObject();是否为空对象 (不含可枚举属性)。
jQuery.isFunction():是否为函数
jQuery.isNumberic():是否为数字
jQuery.isPlainObject():是否为使用“{}”或“new Object”生成对象,而不是浏览器原生提供的对象。
jQuery.isWindow(): 是否为window对象;
jQuery.isXMLDoc(): 判断一个DOM节点是否处于XML文档中。
回顾 整理,留下足迹!!!