for..in loop loops over non-numeric indexes “clean” and “remove”

后端 未结 3 518
醉酒成梦
醉酒成梦 2021-01-29 10:10

This is something very basic I might be missing here but I haven\'t seen such result till now.

I have a for loop where options.headers.length is 3. And in

3条回答
  •  难免孤独
    2021-01-29 10:26

    1. don use just index (as that is = window.index = global = bad) use var index (read more here https://www.google.pl/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=globals+javascript+bad)

    2. you have to check does the array has it as own property or maybe its some function (more after answer)


    for (var index in options.headers) {
        if (options.headers.hasOwnProperty(index) {
             // code here
        }
    }
    

    more about #2:

    let's say we have

    var array = [0,1,2,3];
    

    and besides that, extending array with function (arrays can have functions in javascript and strings too)

    Array.prototype.sayHello = function() {
        alert('Hello');
    };
    

    then your loop would print sayHello as part of the array, but that's not it's own property, only the arrays

提交回复
热议问题