Home  >  Article  >  Web Front-end  >  The use of for-in loops and for loops to traverse arrays

The use of for-in loops and for loops to traverse arrays

一个新手
一个新手Original
2017-09-26 09:32:254048browse

When I was writing code today, some inexplicable things appeared when using a for-in loop to traverse the array. I checked the information later. Only then did I know the difference between for-in loop and for loop.
The for -in loop is iteration. It iterates all the properties and methods of the current object. It will filter out the properties and methods originally written by the system. If we add properties and methods to it. During for-in, these properties and methods we added will be traversed.
For example: I added a method to the array in js

//Array中的prototype方法就是给所有的数组都添加了一个新定义的方法名字为unique
 Array.prototype.unique = function(){
        alert("unique");
    }    var arr = [0,1,2];

Then when the above code is executed, this method will be added to all arrays. So next time when using the for-in loop, this function will be traversed.

for(var i in arr){
    concole.log(arr[i]);
}

The printing result at this time is
The use of for-in loops and for loops to traverse arrays
If you don't want to traverse your own defined methods, the system provides a method to determine whether the current property is added later instead of the system's original one, which is array.hasOwnProperty(i)
If the above code does not want to print the custom method, then judge this thing

for(var i in arr){        
    if(!arr.hasOwnProperty(i)){            
    continue;
        }            
        console.log(arr[i]);
    }

Use this method to judge whether i is a newly added attribute or method later. If it is a newly added one, then skip the execution. next.


Of course, if it is an array, we'd better not use for - in loop to traverse, it's better to use for loop to write, so as to avoid some unnecessary trouble

The above is the detailed content of The use of for-in loops and for loops to traverse arrays. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Scripting HTTP with AjaxNext article:Scripting HTTP with Ajax