When do I need to use hasOwnProperty()?

前端 未结 3 1078
轻奢々
轻奢々 2020-11-30 10:58

I read that we should always use hasOwnProperty when looping an object, because the object can be modified by something else to include some keys we don\'t want.

But

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-30 11:42

    When you're using for (var key in obj) it will loop through the given object + its parent objects' properties on the prototype chain until it reaches the end of the chain. As you want to check only a specific object's properties, you need to use hasOwnProperty.

    This is not needed in for (var i = 0; i < length; i++) or data.forEach().

提交回复
热议问题