zoukankan      html  css  js  c++  java
  • JS中类型检测方式

    在js中的类型检测目前我所知道的是三种方式,分别有它们的应用场景:

    1、typeof:主要用于检测基本类型.

    typeof undefined;//=> undefined
    typeof 'a';//=> string
    typeof 1;//=> number
    typeof true;//=> boolean
    typeof {};//=> object
    typeof [];//=> object
    typeof function() {};//=> function
    typeof null;//=> object

    2、instanceof:主要用于检测引用类型(左边是对象,右边是函数.根据对象的原形链往上找,如果原形链上有右边函数.prototype,返回true;否则返回false).

    var obj = {}; obj instanceof Object; //=> true; 
    var arr = []; arr instanceof Array; //=> true;
    var fn = function() {}; fn instanceof Function; //=> true;

    3、Object.prototype.toString.call(sth):由于原形链的检测有漏洞(原型是可以改变的),所以会造成检测结果不准确,所以可以采用此种形式.

    var toString = Object.prototype.toString;
    toString.call(undefined);//=> [object Undefined]
    toString.call(1);//=> [object, Number]
    toString.call(NaN);//=> [object, Number]
    toString.call('a');//=> [object, String]
    toString.call(true);//=> [object, Boolean]
    
    toString.call({});//=> [object, Object]
    toString.call(function() {});//=> [object, Function]
    toString.call([]);//=> [object, Array]
    toString.call(null);//=> [object, Null]
  • 相关阅读:
    判断一个点是否在一个不规则多边形内算法
    vue-cli 3.0 安装和创建项目流程
    微信小程序分享朋友圈的实现思路与解决办法
    vue2.0中关于active-class
    Nginx服务启动脚本
    Linux系统优化
    URL检测脚本
    Mysql读写分离php脚本
    Memcahed服务异常监控脚本
    一致性哈希算法PHP测试片段
  • 原文地址:https://www.cnblogs.com/littlebirdlbw/p/6860038.html
Copyright © 2011-2022 走看看