Check that value is object literal?

后端 未结 12 671
逝去的感伤
逝去的感伤 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:07

    Vanilla Javascript version of JQuery.isPlainObject function.

    var class2type = {};
    var toString = class2type.toString;
    var getProto = Object.getPrototypeOf;
    var hasOwn = class2type.hasOwnProperty;
    var fnToString = hasOwn.toString;
    var ObjectFunctionString = fnToString.call(Object);
    
    function isPlainObject(obj) {
      var proto, Ctor;
    
      // Detect obvious negatives
      // Use toString instead of jQuery.type to catch host objects
      if (!obj || toString.call(obj) !== "[object Object]") {
        return false;
      }
    
      proto = getProto(obj);
    
      // Objects with no prototype (e.g., `Object.create( null )`) are plain
      if (!proto) {
        return true;
      }
    
      // Objects with prototype are plain iff they were constructed by a global Object function
      Ctor = hasOwn.call(proto, "constructor") && proto.constructor;
      return typeof Ctor === "function" && fnToString.call(Ctor) === ObjectFunctionString;
    }
    

    Example:

    isPlainObject({}) // true
    isPlainObject( "test" ) // false
    

提交回复
热议问题