Why is there no forEach method on Object in ECMAScript 5?

后端 未结 3 638
时光说笑
时光说笑 2021-01-31 08:34

ECMAScript 5\'s array.forEach(callback[, thisArg]) is very convenient to iterate on an array and has many advantage over the syntax with a for:

  • It\'s
3条回答
  •  感动是毒
    2021-01-31 08:53

    Well, it's pretty easy to rig up yourself. Why further pollute the prototypes?

    Object.keys(obj).forEach(function(key) {
      var value = obj[key];
    });
    

    I think a big reason is that the powers that be want to avoid adding built in properties to Object. Objects are the building blocks of everything in Javascript, but are also the generic key/value store in the language. Adding new properties to Object would conflict with property names that your Javascript program might want to use. So adding built in names to Object is done with extreme caution.

    Array is indexed by integers, so it doesn't have this issue.

    This is also why we have Object.keys(obj) instead of simply obj.keys. Pollute the Object constructor as that it typically not a big deal, but leave instances alone.

提交回复
热议问题