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


当前回答

简单的工作解决方案:

function isObject(value) {
    return !(value instanceof Date) && !Array.isArray(value) && !Object.is(value, null) && !Object.is(value, undefined) && !(value instanceof Function)
}

其他回答

function isObjectLike(value) {
  return value != null && typeof value == 'object' && !Array.isArray(value);
}

基于lodash

如果typeof yourVariable==“object”,则它是一个对象或null。

如果要排除null、数组或函数,只需执行以下操作:

if (
    typeof yourVariable === 'object' &&
    !Array.isArray(yourVariable) &&
    yourVariable !== null
) {
    executeSomeCode();
}

我认为有这么多答案的原因是,无论你是否喜欢,很多东西都是javascript中的对象。

您可以像任何其他对象一样迭代数组的“键”。。。

var key, 
    arr = ['one', 'two', 'three'];
for (key in arr)
    console.log(`${key}=${arr[key]}`);

console.log(arr[1]);
console.log(arr['1']);

// 0=one
// 1=two
// 2=three
// two
// two

数组是特殊的(像许多对象一样),因为它有一些通用对象没有的财产/方法(例如长度、forEach等)。

所以这个问题应该是:如何过滤特定类型的对象?

毕竟,我可以很容易地实现自己的数组、正则表达式或符号,它也可以是一个对象,但可能会通过各种“它是真实对象吗?”测试。。。。因为它是一个真实的物体。

所以你想过滤到某些类型的javascript对象。。。

最好的方法是只做特性测试。例如,您是否关心它是否具有长度属性?示例:浏览器中的NodeList看起来像一个数组,可以像数组一样迭代,但不是数组。

无论如何,如果您只想过滤掉特定类型的对象,那么只有您才能定义要过滤的对象。是否要筛选出RegExp?日期大堆浏览器DOM对象?只有你才能决定你的过滤链是什么样子。您可以使用直通开关来构建紧凑的过滤器。


function typeOfIs(val, type) {
    return typeof val == type;
}

function constructorIs(val, constructor) {
    return val && constructor && val.constructor === constructor;
}

function isObject(val) {
    // catch the easy non-object values
    if (!typeOfIs(val, 'object')) 
        return false;

    // catch the cases you don't want to consider to be 
    // "real" objects for your use-case
    switch (true) {
        case val === null:
        case Array.isArray(val):
        case typeOfIs(val, 'function'):
        case constructorIs(val, RegExp):
            return false;
        default:
            return true;
    }
}
function test(val) {
    console.log(Object.prototype.toString.call(val)+': '+isObject(val));
}
test(undefined);
test(null);
test(function () {});
test(Symbol('foo'));
test(1);
test(true);
test(false);
test('hello world');
test([]);
test(/.*/g);
test(new Date()); // true (because we didn't filter for it)
test({});  // true

特性测试

但更好的方法可能是询问为什么要筛选,或者只测试给定变量上是否存在您需要/期望的财产/函数。。。如果它们存在,使用变量,不要担心它是某种类型的对象还是另一种类型的对象。如果它们不存在,则抛出一个API错误,即您被传递了一些类型不正确的值(即缺少预期的财产/函数)。

e.g.

if (typeof someVariable.hasOwnProperty == 'function')
    // ...

我从这个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

您可以使用JSON.stringify来测试Object,如下所示:

var测试={}if(JSON.stringify(测试)[0]==“{”){console.log('这是一个对象')}