Javascript数据类型检测

1.typeof

//typeof 直接在计算机底层基于数据类型的值(二进制)进行检测
//null二进制 000   对象都是000开头的  所以null也被检测为 "object"
//typeof 普通对象/数组对象/正则对象/日期对象  "object"
typeof ''
"string"
typeof 12
"number"
typeof Array
"function"
typeof {}
"object"
typeof null
"object"
typeof NaN
"number"

2.instanceof 当前实例是否属于这个类

//instanceof 基于原型链检测  只要当前类在原型链上 都为true
let arr = []
console.log(arr instanceof Array)  //=>true
console.log(arr instanceof RegExp)  //=>false
console.log(arr instanceof Objcet)  //=>true

特殊情况

function Fn(){
    this.x = 100;
}
Fn.prototype = Object.create(Array.prototype);
let f = new Fn;
console.log(f instanceof Array) //=>true   无数组length属性

自己实现一个instanceof

function instance_of(example,classFunc){
    let classFuncPrototype = classFunc.prototype,
        proto = Object.getPrototypeOf(example);//example.__proto__  IE不支持
                                      //所以用Objcet.getPrototypeOf()方法
    while(true){
        if(proto === null){
            //Objcet.prototype.__proto__ = null
            return false
        }
        if(prototype === classFuncPrototype){
            //查找过程中发下有匹配到,则证明实例是这个类的一个实例
            return true
        }
        proto = Object.getPrototypeOf(proto)
    }
}

3.constructor 比instanceof好用一些(支持基本类型)

let arr = [];
console.log(arr.constructor === Array); // true
console.log(arr.constructor === RegExp); // false
console.log(arr.constructor === Object); // false
//constructor 可以随便改   结果不准
Number.prototype.constructor = 'AA';
let n = 1;
console.log(n.constructor === Number); // false 

4.Object.propertype.toString.call([value]) 标准方法

// let obj = {
//     name: 'hello world'
// };
// obj.toString(); =>"[object Object]"
// -> toString方法执行,this是obj,所以检测是obj它的所属类信息
// 推测:是不是只要把Object.prototype.toString执行,让它里面的this变为
//要检测的值,那就能返回当前值所属类的信息

  * + Object.prototype.toString.call([value]) 
 * + 标准检测数据类型的办法:Object.prototype.toString不是转换为字符串,是返
 * + 回当前实例所属类的信息
 * + 标准检测的办法 "[object Number/String/Boolean/Null/Undefined/Symbol/Object/Array/RegExp/Date/Function]"
 */
//Jquery里的方法
(function () {
    var class2type = {};
    var toString = class2type.toString; //=>Object.prototype.toString

    // 设定数据类型的映射表
    ["Boolean", "Number", "String", "Function", "Array", "Date", "RegExp", "Object", "Error", "Symbol"].forEach(name => {
        class2type[`[object ${name}]`] = name.toLowerCase();
    });

    function toType(obj) {
        if (obj == null) {
            // 传递的值是null或者undefined,就返回对应的字符串
            return obj + "";
        }
        // 基本数据类型都采用typeof检测
        return typeof obj === "object" || typeof obj === "function" ?
            class2type[toString.call(obj)] || "object" :
            typeof obj;
    }

    window.toType = toType;
})();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值