For ... in for an array of strings

This question already has an answer here:

  • For-each over an array in JavaScript? 23 answers

  • for..in loops over enumerable properties and arrays have numerical properties which acts as index. It is to be used with only objects.

    Doing so with Arrays will also give you properties which you won't be interested in(such as those properties which are on the higher chain of prototypic inheritance from Object object)

    So use a simple for loop or Array.forEach

    products.forEach(function(str){
       console.log(str);
    });
    // or
    for(var i = 0; i < products.length; i++)
       console.log(products[i]);
    

    That's because in your case, variable x is holding the array item's index, and not the value. Instead of x , you should use products[x] .

    products = ["Item1", "Item2", "Item3"];
    for (var x in products) {
      debugger;
      console.log(products[x]);
    }
    

    Now, instead of:

    0
    1
    2
    

    you'll get

    Item1
    Item2
    Item3
    

    Iterate over the array like this. U use var in arr if you want to iterate over properties of an object, not an array!

    var products = ["Item1", "Item2", "Item3"];
    for (var i =0; i< products.length;i++) {
      debugger;
      console.log(products[i]);
      // x === "0" instead of "Item1"
    }
    
    链接地址: http://www.djcxy.com/p/12076.html

    上一篇: jquery预加载图像1槽40

    下一篇: 对于...中的字符串数组