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

后端 未结 3 492
醉酒成梦
醉酒成梦 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:25

    if you don't want to iterate clean and remove then change the loop to:

    for (var i=0; i< options.headers.length;i++){
    //use i for getting the array data
    }
    

    if you use for (index in options.headers) it will iterate for non-numeric keys also.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-29 10:27

    I assume that options.headers is an Array?

    This happens when you (or some framework you load) adds methods to the Array prototype. The "for in" loop will enumerate also these added methods. Hence you should do the loop for an array with:

    for (var i = 0; i < options.headers.length; i++)
    

    That way you will only get the real values instead of added methods.

    0 讨论(0)
提交回复
热议问题