zoukankan      html  css  js  c++  java
  • JavaScript Patterns 2.4 For-in loop

    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]);
        }
    }
  • 相关阅读:
    30分钟掌握ES6/ES2015的核心内容(上)
    rem 响应式用法
    angular框架MVVM
    vue3 + vite + elmentui
    vue3 + vite + elmentui
    vue3 + vite 开发新项目
    滚动条滚动加一个进度条
    jquery 截取页面 url ,切换新的url 跳转
    h5,css3
    前端模板预编译技术
  • 原文地址:https://www.cnblogs.com/haokaibo/p/for-in-loop.html
Copyright © 2011-2022 走看看