需要预习:call , typeof, js数据类型

1. isFunction中typeof的不靠谱

源码:

var isFunction = function isFunction( obj ) {

// Support: Chrome <=57, Firefox <=52
// In some browsers, typeof returns "function" for HTML <object> elements
// (i.e., `typeof document.createElement( "object" ) === "function"`).
// We don't want to classify *any* DOM node as a function.
return typeof obj === "function" && typeof obj.nodeType !== "number";
};

typeof 是为了区分数据类型,下面是MDN中总结的typeof中所有存在的值

问题一:我们都知道typeof null 出来的结果是‘object’,可这是为啥呢?MDN给出了答案 :因为null是空指针,而空指针在大多数平台中使用0x00表示,而js在实现初期通过用 0 作为对象的标签,所以对null也被判断为object。

问题二:既然typeof能够判断出function,为何jquery额外判断   typeof obj.nodeType !== "number" 呢?

long long ago,在那些古老的浏览器中:

1. typeof document.body.childNodes  // function   这在古老的 safari 3 中会出现

2.typeof document.createElement("object")  // function 同理还有 'embed'  'applet' ,  在古老的firefox中会出现,目前新版本不会存在

3.typeof /s/ // function  这种情况会在古老浏览器中出现,目前都会被判定为 object

通过以上问题我们可以看出,通过typeof判断数据类型在古老的浏览器中是极为不靠谱的,所以在jquery的isFunction的判断中额外添加了判断 检测对象是否为dom 对象

2.靠谱的数据类型判断 

源码:

var class2type = {};

var toString = class2type.toString;

// Populate the class2type map,这里并没有undefined
jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
function( i, name ) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
} ); function toType( obj ) {
if ( obj == null ) {
return obj + "";
} // Support: Android <=2.3 only (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call( obj ) ] || "object" :
typeof obj;
}

在代码中jquery做了这几件事:

1.jquery先提取出toString 这个方法

2.将写好的类型字符串分割并存入class2type中,class2type 数据结构如下:

3.定义toType方法,因为 toString(null)会得出‘ [object Undefined]’的结果,所以需要把null单独判断,注意null是没有toString这个方法的,所以通过 obj+''这个方式得到 'null'

4.在单独判断null后是一个三元运算符:等价于

 if(typeof obj === "object" || typeof obj === "function"){
// 因为上文提到存在typeof /s/ 为 function的情况,所以需要toString详细判断
// 对于判断不出的数据类型默认为object
retrun class2type[ toString.call( obj ) ] || "object";
} else {
// 通过上面typeof对类型判断的表格,判断非object function还是很可靠的,所以直接用原生方法
return typeof obj;
}

结论: 通过用toString方法可以判断出Boolean、Number、 String、 Function、 Array、 Date、 RegExp、 Object、 Error、 Symbol、undefined 这些数据类型,但是并不能判断出null,所以要综合判断,就酱

除此之外jquery还额外判断了当前对象是否为window,只用了如下的方法:

var isWindow = function isWindow( obj ) {
return obj != null && obj === obj.window;
};

前方的obj!=null 是为了防止开发人员在调用函数 isWindow时传入null 、undefined的时候报Uncaught TypeError: Cannot read property 'window' of null/undefined的错误。

还有isArrayLike,判断当前对象是不是类数组对象,类数组对象是什么,建议大家百度一下

function isArrayLike( obj ) {

    // Support: real iOS 8.2 only (not reproducible in simulator)
// `in` check used to prevent JIT error (gh-2145)
// hasOwn isn't used here due to false negatives
// regarding Nodelist length in IE
var length = !!obj && "length" in obj && obj.length,
type = toType( obj ); if ( isFunction( obj ) || isWindow( obj ) ) {
return false;
} return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}

首先判断obj中是否有length属性并取出length

然后排除obj是否是window 及 function

最后取值条件:1.是否是array(类数组对象集合当然包括数组) 2.存在length属性但length是0  3.判定length是数字且大于零,并在obj对象中存在length-1属性

看jquery3.3.1学js类型判断的技巧的更多相关文章

  1. 类型和原生函数及类型转换(二:终结js类型判断)

    typeof instanceof isArray() Object.prototype.toString.call() DOM对象与DOM集合对象的类型判断 一.typeof typeof是一个一元 ...

  2. JS类型判断typeof PK {}.toString.call(obj)

    参考链接:https://www.talkingcoder.com/article/6333557442705696719 先看typeof <!doctype html> <htm ...

  3. js类型判断-丰富加好用

    一, 自己有时候写一些东西,要做类型判断,还有测试的时候,对于原生的和jQuery中的类型判断,实在不敢恭维,所以就写了一个好用的类型判断,一般情况都够用的. function test(type) ...

  4. JS类型判断&原型链

    JS类型检测主要有四种 1.typeof Obj 2.L instanceof R 3.Object.prototype.toString.call/apply(); 4.Obj.constructo ...

  5. js类型判断:typeof与instanceof

    typeof用以获取一个变量或者表达式的类型,typeof一般只能返回如下几个结果: number,boolean,string,function(函数),object(NULL,数组,对象),und ...

  6. js类型判断

    console.log('---------------------'); var a="string"; console.log(a); //string var a=1; co ...

  7. js类型判断及鸭式辨型

    目录 instanceof constructor 构造函数名字 鸭式辨型 三种检测对象的类方式: instanceof.constructor .构造函数名字 用法如下: 1)instanceof ...

  8. js类型判断的方法

    var arr=[]; alert(Object.prototype.toString.call(arr)=='[object Array]');

  9. js 类型判断

随机推荐

  1. bzoj1069-最大土地面积

    题目 给定\(n\ (n\le 2000)\)个坐标,求四个坐标使得围起来的四边形面积最大. 分析 最暴力的想法是枚举四个点,然而肯定超时.接着不知道怎么想到中途相遇,然而一点关系都没有.这里用到了一 ...

  2. 【bzoj5064】B-number 数位dp

    题目描述 B数的定义:能被13整除且本身包含字符串"13"的数. 例如:130和2613是B数,但是143和2639不是B数. 你的任务是计算1到n之间有多少个数是B数. 输入 输 ...

  3. 【bzoj4832】[Lydsy2017年4月月赛]抵制克苏恩 概率期望dp

    题目描述 你分别有a.b.c个血量为1.2.3的奴隶主,假设英雄血量无限,问:如果对面下出一个K点攻击力的克苏恩,你的英雄期望会受到到多少伤害. 输入 输入包含多局游戏. 第一行包含一个整数 T (T ...

  4. openstack之Glance介绍

    什么是Glance glance即image service(镜像服务),是为虚拟机的创建提供镜像服务 为什么要有Glance 我们基于openstack是构建基本的Iaas平台对外提供虚机,而虚机在 ...

  5. [BZOJ2821]作诗

    description 在线询问区间内出现次数为正偶数的数的种数. data range \[n,m\le 10^5\] solution 分块大法好 首先离散化权值 这种对于权值做询问并且询问放在一 ...

  6. 洛谷3763:[TJOI2017]DNA——题解

    https://www.luogu.org/problemnew/show/P3763 加里敦大学的生物研究所,发现了决定人喜不喜欢吃藕的基因序列S,有这个序列的碱基序列就会表现出喜欢吃藕的性状,但是 ...

  7. Numpy模块(数值计算)

    Numpy是高性能科学计算和数据分析的基础包.它是pandas等其他各种工具的基础. NumPy的主要功能: ndarray,一个多维数组结构,高效且节省空间 无需循环对整组数据进行快速运算的数学函数 ...

  8. win10下ndk编译arm可执行体

    编译参考文章 http://blog.csdn.net/john_1984/article/details/12622215 一.编写soLoader主文件 soLoader.c内容: #includ ...

  9. Codeforces Round #344 (Div. 2) B

    B. Print Check time limit per test 1 second memory limit per test 256 megabytes input standard input ...

  10. ACM1198Farm Irrigation

    这个题目好吓人呀!嘿嘿--- 不过仔细分析下就可以啦! #include<iostream> #include<cstring> using namespace std; ; ...