How to quickly clear a JavaScript Object?

后端 未结 8 1129
一个人的身影
一个人的身影 2020-11-27 12:52

With a JavaScript Array, I can reset it to an empty state with a single assignment:

array.length = 0;

This makes the Array \"appear\" empty

8条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 13:11

    ES5

    ES5 solution can be:

    // for enumerable and non-enumerable properties
    Object.getOwnPropertyNames(obj).forEach(function (prop) {
      delete obj[prop];
    });
    

    ES6

    And ES6 solution can be:

    // for enumerable and non-enumerable properties
    for (const prop of Object.getOwnPropertyNames(obj)) {
      delete obj[prop];
    }
    

    Performance

    Regardless of the specs, the quickest solutions will generally be:

    // for enumerable and non-enumerable of an object with proto chain
    var props = Object.getOwnPropertyNames(obj);
    for (var i = 0; i < props.length; i++) {
      delete obj[props[i]];
    }
    
    // for enumerable properties of shallow/plain object
    for (var key in obj) {
      // this check can be safely omitted in modern JS engines
      // if (obj.hasOwnProperty(key))
        delete obj[key];
    }
    

    The reason why for..in should be performed only on shallow or plain object is that it traverses the properties that are prototypically inherited, not just own properties that can be deleted. In case it isn't known for sure that an object is plain and properties are enumerable, for with Object.getOwnPropertyNames is a better choice.

提交回复
热议问题