The difference between for loop and for...in

for(var i in arr)和for(var i=0;i<arr.length;i++)比较

  1. The former loops through attributes, while the latter loops through arrays.
    If the array is expanded in the project, the former cannot be used, otherwise the expanded function body will be returned as data when the array properties are expanded.
    For example, we extend an array property
     Array.prototype.remove = function(val) {
         var index = this.indexOf(val);
         if (index > -1) {
             this.splice(index, 1);
         }
     };
    // 在循环一个数组的时候回出现如下情况
    var arr = [11,22];
    for(var i in arr){
        console.log(i);
    }
    输出结果为0,1,remove

     

  2. The former loop output i is a string (string), the latter is a number (number);

Guess you like

Origin blog.csdn.net/qq_37514029/article/details/84991564