Check that value is object literal?

后端 未结 12 699
逝去的感伤
逝去的感伤 2020-12-01 10:57

I have a value and want to know if it\'s an iteratable object literal, before I iterate it.

How do I do that?

12条回答
  •  再見小時候
    2020-12-01 11:09

    I think a function like this should be native, just like Array.isArray:

    Object.isObject = function(obj) {
        return obj && obj.constructor === this || false;
    };
    

    This one doesn't make function calls nor string comparisons, and doesn't reference global objects (like Object), so it should be quite fast. I don't think this will used in performance intensive tasks though, but whatever.

    I'm not totally convinced about the name... maybe something like Object.isLiteral would be better.

    It can cause problem with host objects, though, but I don't have a test ready.

提交回复
热议问题