Principle

  1. Enumeration should be used to iterate over nonarray objects.
  2. It's important to use the method hasOwnProperty()when iterating over object properties to filter out properties that come down the prototype chain.
// the object
var man = {
hands: 2,
legs: 2,
heads: 1
}; // somewhere else in the code // a method was added to all objects
if (typeof Object.prototype.clone = = = "undefined") {
Object.prototype.clone = function () {};
} // 1. for-in loop
for (var i in man) {
if (man.hasOwnProperty(i)) { // filter
console.log(i, ":", man[i]);
}
} /*
result in the console
hands : 2
legs : 2
heads : 1
*/ // 2. antipattern:
// for-in loop without checking hasOwnProperty()
for (var i in man) {
console.log(i, ":", man[i]);
} /*
result in the console
hands : 2
legs : 2
heads : 1
clone: function()
*/

Call method off of the Object.prototype to avoid naming collisions that man object redefined hasOwnProperty. And use a local variable to cache it.

var i,
hasOwn = Object.prototype.hasOwnProperty;
for (i in man) {
if (hasOwn.call(man, i)) { // filter
console.log(i, ":", man[i]);
}
}

最新文章

  1. SQL执行效率和性能测试方法总结
  2. (转)Java集合框架:HashMap
  3. WS调用的时候报错
  4. Hadoop2.6.0错误
  5. 在VB中利用Nuget包使用SQLite数据库和Linq to SQLite
  6. ruby 疑难点之—— yield 和 yield self
  7. gridControl 中CellValueChanged,ShowingEditor,CustomDrawCell的用法
  8. linux export将PATH环境变量误删了的解决办法
  9. FZU 1063 三维扫描
  10. C语言mktime()
  11. log4j日志的基本使用方法(1)——概述、配置文件
  12. eclipse安装和中文汉化,以及配置
  13. webpack基础
  14. leetcode — single-number-ii
  15. ARM与FPGA通过spi通信设计2.spi master的实现
  16. Java 基础知识点
  17. go语言学习 一
  18. bootstrap datepicker显示日历
  19. python之初识网络
  20. winform,WPF 释放内存垃圾,减少资源占用方法

热门文章

  1. 一天搞定jQuery(三)——使用jQuery完成复选框的全选和全不选
  2. 09Oracle Database 数据表数据插入,更新,删除
  3. Luogu P3110 [USACO14DEC]驮运Piggy Back
  4. 魂酥的LNOI2019滚粗记
  5. Linux---shell基本指令
  6. session--保持登录20分钟,常用与用户登录状态
  7. odoo domain详解
  8. vuex----------state的基础用法
  9. Unity对象的所有组件深拷贝与粘贴
  10. [bzoj 1005][HNOI 2008]明明的烦恼(prufer数列+排列组合)