首页 > 网站 > WEB开发 > 正文

JavaScript Patterns 2.4 For-in loop

2024-04-27 14:23:53
字体:
来源:转载
供稿:网友

javaScript Patterns 2.4 For-in loop

2014-05-19 11:06 by 小郝(Kaibo Hao), ... 阅读, ... 评论, 收藏, 编辑

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 objectvar man = {    hands: 2,    legs: 2,    heads: 1};// somewhere else in the code// a method was added to all objectsif (typeof Object.prototype.clone = = = "undefined") {    Object.prototype.clone = function () {};}// 1. for-in loopfor (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]);    }}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表