Object.prototyep.toString 检查数据类型

文章参考

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

准确检查数据的类型方法

function checkDataType (checkedData){
	return Object.prototype.toString.call(checkedData);
}

1、Object.prototype.toString 方法返回一个表示该对象的字符串

2、所有的对象继承Object类,只是覆盖了 toString 方法,因此无法直接使用toString方法获取数据类型

3、需要以 Function.prototype.call() 或者 Function.prototype.apply() 的形式来调用,把需要检测的对象作为第一个参数传入

/**
         *  判断是否 Object 对象
         * @param obj 被检测数据
         * @returns {boolean}
         */
        isObject : function(obj){
            if('[object Object]' == this.checkDataType(obj)){
                return true;
            }
            return false;
        },

        /**
         *  判断是否 Number 对象
         * @param obj 被检测数据
         * @returns {boolean}
         */
        isNumber : function(obj){
            if('[object Number]' == this.checkDataType(obj)){
                return true;
            }
            return false;
        },

猜你喜欢

转载自hbiao68.iteye.com/blog/2365317