JavaScript Patterns 2.4 For-in loop
2024-09-03 22:24:40
Principle
- Enumeration should be used to iterate over nonarray objects.
- 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]);
}
}
最新文章
- SQL执行效率和性能测试方法总结
- (转)Java集合框架:HashMap
- WS调用的时候报错
- Hadoop2.6.0错误
- 在VB中利用Nuget包使用SQLite数据库和Linq to SQLite
- ruby 疑难点之—— yield 和 yield self
- gridControl 中CellValueChanged,ShowingEditor,CustomDrawCell的用法
- linux export将PATH环境变量误删了的解决办法
- FZU 1063 三维扫描
- C语言mktime()
- log4j日志的基本使用方法(1)——概述、配置文件
- eclipse安装和中文汉化,以及配置
- webpack基础
- leetcode — single-number-ii
- ARM与FPGA通过spi通信设计2.spi master的实现
- Java 基础知识点
- go语言学习 一
- bootstrap datepicker显示日历
- python之初识网络
- winform,WPF 释放内存垃圾,减少资源占用方法
热门文章
- 一天搞定jQuery(三)——使用jQuery完成复选框的全选和全不选
- 09Oracle Database 数据表数据插入,更新,删除
- Luogu P3110 [USACO14DEC]驮运Piggy Back
- 魂酥的LNOI2019滚粗记
- Linux---shell基本指令
- session--保持登录20分钟,常用与用户登录状态
- odoo domain详解
- vuex----------state的基础用法
- Unity对象的所有组件深拷贝与粘贴
- [bzoj 1005][HNOI 2008]明明的烦恼(prufer数列+排列组合)