美文网首页
JavaScript:判断对象类型函数

JavaScript:判断对象类型函数

作者: 勇往直前888 | 来源:发表于2017-05-02 13:37 被阅读865次

    typeof操作符

    • 是操作符,不是函数,后面可以带(),也可以不带()
    • 返回的结果都是小写字母
    • 函数类型返回function
    • 数组,null,等都返回object
    • 适合判断基本类型变量,不适合判断引用类型(都返回object),比如自定义的对象类型
    var message = "some string";
    typeof message;      // "string"
    typeof (message) ;   // "string"
    
    typeof null;           // "object"
    typeof Array;          // "function"
    typeof [1, 2, 333];    // "object"
    typeof undefined;      // "undefined"
    typeof 100;            // "number"
    typeof false;          // "boolean"
    typeof {a: 1};         // "boolean"
    
    • 如果我们想要判断一个变量是否存在,可以使用typeof,不能使用if(a)a未声明,则报错。
    if(typeof a != "undefined"){
        //变量存在
    } else {
        //变量不存在
    }
    

    instanceof运算符

    instanceof运算符用来判断一个构造函数的prototype属性所指向的对象是否存在另外一个要检测对象的原型链上

    • 返回的结果是一个布尔值true or false
    • 主要用于自定义对象的判断
    function Person(){};
    function Student(){};
    var p = new Person();
    Student.prototype = p;               //继承原型
    var s = new Student();
    console.log(s instanceof Student);   //true
    console.log(s instanceof Person);    //true
    

    js中typeof和instanceof用法区别
    js中的instanceof运算符

    Object.prototype.toString.call(object) 方法

    • 返回的结果类似“[object Null]”形式
    • 基本类型和引用类型都适用,比如,Array,Date
    // 基本类型
    Object.prototype.toString.call(null);          // “[object Null]”
    Object.prototype.toString.call(undefined);     // “[object Undefined]”
    Object.prototype.toString.call("abc");         // “[object String]”
    Object.prototype.toString.call(123);           // “[object Number]”
    Object.prototype.toString.call(true);          // “[object Boolean]”
    // 函数类型
    function fn(){console.log("test");}
    Object.prototype.toString.call(fn);              // “[object Function]”
    // 日期类型
    var date = new Date();
    Object.prototype.toString.call(date);            // “[object Date]”
    // 数组类型
    var arr = [1,2,3];
    Object.prototype.toString.call(arr);             // “[object Array]”
    // 正则表达式
    var reg = /[hbc]at/gi;
    Object.prototype.toString.call(reg);             // “[object RegExp]”
    
    • 自定义的类型还是返回“[object Object]”
    function Person(name, age) {
        this.name = name;
        this.age = age;
    }
    var person = new Person("Rose", 18);
    Object.prototype.toString.call(person); //“[object Object]”
    
    • 通过对结果取自字符串,大小转小写等操作,可以输出"null"等结果
    function type(object) {
       return Object.prototype.toString.call(object).slice(8,-1).toLowerCase();
    }
    type(1)              // "Number"
    type("abc")          // "String"
    

    关于Object.prototype.toString.call
    Object.prototype.toString.call()方法浅谈
    js中通过Object.prototype.toString方法----精确判断对象的类型

    判断类型工具

    比如文件名可以命名为type.js

    • 获取类型字符串,全小写
    • 判断是否是某种类型的方便函数
    function typeString(object) {
       return Object.prototype.toString.call(object).slice(8,-1).toLowerCase();
    }
    
    function isNull(object) {
        return typeString(object) === 'null';
    }
    
    function isUndefined(object) {
        return typeString(object) === 'undefined';
    }
    
    function isNumber(object) {
        return typeString(object) === 'number';
    }
    
    function isString(object) {
        return typeString(object) === 'string';
    }
    
    function isBoolean(object) {
        return typeString(object) === 'boolean';
    }
    
    function isFunction(object) {
        return typeString(object) === 'function';
    }
    
    function isArray(object) {
        return typeString(object) === 'array';
    }
    
    function isDate(object) {
        return typeString(object) === 'date';
    }
    
    function isRegExp(object) {
        return typeString(object) === 'regexp';
    }
    
    function isObject(object) {
        return typeString(object) === 'object';
    }
    
    module.exports = {
        typeString : typeString,
        isNull : isNull,
        isUndefined : isUndefined,
        isNumber : isNumber,
        isString : isString,
        isBoolean : isBoolean,
        isFunction : isFunction,
        isArray : isArray,
        isDate : isDate,
        isRegExp : isRegExp,
        isObject : isObject,
    }
    

    同时,可以写一个测试文件,比如命名为type_test.js

    const type = require('./type.js')
    const log = console.log;
    
    // 基本类型
    log(type.typeString(123));
    log(type.isNumber(123));
    log(type.typeString(null));
    log(type.isNull(null));
    log(type.typeString(undefined));
    log(type.isUndefined(undefined));
    log(type.typeString(`123`));
    log(type.isString('123'));
    log(type.typeString(true));
    log(type.isBoolean(true));
    
    // 函数类型
    function fn() {
        console.log('test');
    }
    log(type.typeString(fn));
    log(type.isFunction(fn));
    
    // 日期类型
    var date = new Date();
    log(type.typeString(date));
    log(type.isDate(date));
    
    // 数组类型
    var array = [1,2,3];
    log(type.typeString(array));
    log(type.isArray(array));
    
    // 正则表达式
    var reg = /[hbc]at/gi;
    log(type.typeString(reg));
    log(type.isRegExp(reg));
    
    // 自定义类型
    function Person(name, age) {
        this.name = name;
        this.age = age;
    }
    var person = new Person("Rose", 18);
    log(type.typeString(person));
    log(type.isObject(person));
    
    • 如果只是导出一个函数,获取对象的类型字符串,作为全局函数来使用,那么可以简单一点。
    module.exports = function typeString(object) {
       return Object.prototype.toString.call(object).slice(8,-1).toLowerCase();
    }
    

    typeofJavaScript的操作符,所以这里函数取名有意避开,用了一个typeString。当然,用其他名字也是可以的,比如直接type

    相关文章

      网友评论

          本文标题:JavaScript:判断对象类型函数

          本文链接:https://www.haomeiwen.com/subject/arlctxtx.html