如何检查值是否是JavaScript中的对象?


当前回答

这取决于用例,如果我们不想让数组和函数成为Object,我们可以使用undercore.js内置函数。

    function xyz (obj) { 
       if (_.isObject(obj) && !_.isFunction(obj) && !_.isArray(obj)) {
         // now its sure that obj is an object 
       } 
    }

其他回答

试试这个

if (objectName instanceof Object) {
  alert('Not an object');
}
else {
  alert('An object');
}

isObject()使用可选链接和最新标准检查传递的参数是否为对象:

const isObject = (value) => { 
    return value?.constructor === Object;
}

我从这个SO问题中找到了一种“新”方法来进行这种类型检查:为什么instanceof对某些文本返回false?

在此基础上,我创建了一个类型检查函数,如下所示:

function isVarTypeOf(_var, _type){
    try {
        return _var.constructor === _type;
    } catch(ex) {
        return false;         //fallback for null or undefined
    }
}

那么你可以这样做:

console.log(isVarTypeOf('asdf', String));   // returns true
console.log(isVarTypeOf(new String('asdf'), String));   // returns true
console.log(isVarTypeOf(123, String));   // returns false
console.log(isVarTypeOf(123, Number));   // returns true
console.log(isVarTypeOf(new Date(), String));   // returns false
console.log(isVarTypeOf(new Date(), Number));   // returns false
console.log(isVarTypeOf(new Date(), Date));   // returns true
console.log(isVarTypeOf([], Object));   // returns false
console.log(isVarTypeOf([], Array));   // returns true
console.log(isVarTypeOf({}, Object));   // returns true
console.log(isVarTypeOf({}, Array));   // returns false
console.log(isVarTypeOf(null, Object));   // returns false
console.log(isVarTypeOf(undefined, Object));   // returns false
console.log(isVarTypeOf(false, Boolean));   // returns true

这在Chrome 56、Firefox 52、Microsoft Edge 38、Internet Explorer 11和Opera 43上进行了测试

编辑:如果您还想检查变量是否为空或未定义,则可以使用以下方法:

function isVarTypeOf(_var, _type){
    try {
        return _var.constructor === _type;
    } catch(ex) {
        return _var == _type;   //null and undefined are considered the same
        // or you can use === if you want to differentiate them
    }
}

var a = undefined, b = null;
console.log(isVarTypeOf(a, undefined)) // returns true
console.log(isVarTypeOf(b, undefined)) // returns true
console.log(isVarTypeOf(a, null)) // returns true

财务评论更新:接受挑战:D

如果要松散比较对象,可以尝试以下方法:

function isVarTypeOf(_var, _type, looseCompare){
    if (!looseCompare){
        try {
            return _var.constructor === _type;
        } catch(ex){
            return _var == _type;
        }
    } else {
        try{
            switch(_var.constructor){
                case Number:
                case Function:
                case Boolean:
                case Symbol:
                case Date:
                case String:
                case RegExp:
                    // add all standard objects you want to differentiate here
                    return _var.constructor === _type;
                case Error:
                case EvalError:
                case RangeError:
                case ReferenceError:
                case SyntaxError:
                case TypeError:
                case URIError:
                    // all errors are considered the same when compared to generic Error
                    return (_type === Error ? Error : _var.constructor) === _type;
                case Array:
                case Int8Array:
                case Uint8Array:
                case Uint8ClampedArray:
                case Int16Array:
                case Uint16Array:
                case Int32Array:
                case Uint32Array:
                case Float32Array:
                case Float64Array:
                    // all types of array are considered the same when compared to generic Array
                    return (_type === Array ? Array : _var.constructor) === _type;
                case Object:
                default:
                    // the remaining are considered as custom class/object, so treat it as object when compared to generic Object
                    return (_type === Object ? Object : _var.constructor) === _type;
            }
        } catch(ex){
            return _var == _type;   //null and undefined are considered the same
            // or you can use === if you want to differentiate them
        }
    }
}

这样,你就可以像finance的评论一样:

isVarTypeOf(new (function Foo(){}), Object); // returns false
isVarTypeOf(new (function Foo(){}), Object, true); // returns true

or

Foo = function(){};
Bar = function(){};
isVarTypeOf(new Foo(), Object);   // returns false
isVarTypeOf(new Foo(), Object, true);   // returns true
isVarTypeOf(new Bar(), Foo, true);   // returns false
isVarTypeOf(new Bar(), Bar, true);   // returns true
isVarTypeOf(new Bar(), Bar);    // returns true

大多数类型的obj[index]=='object'被使用,但它也会返回作为对象的函数和#document。这取决于你是否需要将其包括在结果中。

基本上,您可以通过检查控制台中的输出来过滤特定元素是否为对象的测试代码。在这里,您可以仅为示例运行代码:

函数cekObject(obj,index){if(!obj.tagName){//测试用例#1if(对象类型==“对象”){console.log('obj['+index+']被列为对象');} }}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js“></script><脚本>函数updateFilters(){var对象=$('.j-image');$('.juicer feed').empty();for(对象中的var索引){cekObject(对象[index],索引);}; }</script><ul class=“榨汁机饲料”数据饲料id=“chetabahana”数据after=“updateFilters()”></ul><script src=“https://assets.juicer.io/embed.js“></script>

在阅读并尝试了许多实现之后,我注意到很少有人尝试检查JSON、Math、文档或原型链长度超过1步的对象等值。

我认为,与其检查变量的类型,然后删除边缘事例,不如尽可能简单地进行检查,以避免在添加了注册为“对象”类型的新原语或本地对象时进行重构。

毕竟,typeof运算符会告诉您某个对象是否是JavaScript的对象,但JavaScript对对象的定义对于大多数真实场景来说太宽泛了(例如typeof null==“object”)。下面是一个函数,它通过基本上重复两次检查来确定变量v是否为对象:

只要v的字符串化版本为“[object object]”,就会启动一个循环。我希望函数的结果与下面的日志完全相同,所以这是我最终得出的唯一“对象性”标准。如果失败,函数将立即返回false。v被链中的下一个原型替换为v=Object.getPrototypeOf(v),但也在之后直接求值。当v的新值为null时,这意味着包括根原型(很可能是链中唯一的原型)在内的每个原型都通过了while循环中的检查,我们可以返回true。否则,新的迭代开始。

函数isObj(v){while(Object.product.toString.call(v)=='[Object Object]')if((v=Object.getPrototypeOf(v))==null)返回truereturn false}console.log('FALSE:')console.log('[]->',isObj([]))console.log('ull->',isObj(null))console.log('文档->',isObj(文档))console.log('JSON->',isObj(JSON))console.log('function->',isObj(函数(){}))console.log('newDate()->',isObj(newDate(()))console.log('RegExp->',isObj(/./))console.log('TRUE:')console.log(“{}->”,isObj({}))console.log('newObject()->',isObj(newObject(()))console.log('新对象(null)->',isObj(新对象(空)))console.log('newObject({})->',isObj(newObject({foo:'bar'})))console.log('Object.prototype->',isObj(Object.prototype))console.log('Object.create(null)->',isObj(Object.create(null)))console.log(“Object.create({})->”,isObj(Object.create({foo:'bar'})))console.log(“deep继承->”,isObj(Object.create(Object.create({foo:'bar'}))))