分享一个常用的数据类型检测与判空方法方案

318 阅读12分钟
         // 部署类型检测方法
        function deployTypeCheck() {
            function toTypeString(obj) {
                return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
            }

            var funsMap = {
                isNumber: 'number',
                isString: 'string',
                isArray: 'array',
                isObject: 'object',
                isDate: 'date',
                isRegexp: 'regexp',
                isFunction: 'function'
            }

            Object.keys(funsMap).forEach(function (key) {
                Object.prototype[key] = function () {
                    return toTypeString(this) === funsMap[key]
                }
            })

            // 判空操
            Object.prototype.isEmpty = function () {
                if (this.isArray() || this.isString()) return this.length === 0;

                if (this.isObject()) return Object.keys(this).length === 0;

                return true;
            }
        }

        deployTypeCheck();

至此,我们已经见常见的数据类型检测与判空方法部署到Object原型上,接下来我们让我们测试一下

        var num = 2;
        var str = '2';
        var arr = ['1', '2'];
        var obj = { '2': 2 };
        var Null = null;
        var undef = undefined;
        var date = new Date()

        console.log('check_number_isNumber', num.isNumber())
        console.log('check_number_isString', num.isString())
        console.log('check_array_isNumber', arr.isNumber())
        console.log('check_array_isArray', arr.isArray())
        console.log('check_date_isDate', date.isDate())
        console.log('check_date_isObject', date.isObject())

        console.log('check_array_isEmpty1', [].isEmpty())
        console.log('check_array_isEmpty2', ['23'].isEmpty())
        console.log('check_obj_isEmpty1', {}.isEmpty())
        console.log('check_obj_isEmpty2', { 2: '2' }.isEmpty()

结果如下:

采用Object原型部署检测方法可以很便利地使用这些方法,一步到胃,有何不可~

如果你有更好的方案,我们评论区见