Home > Article > Web Front-end > The use of for-in loops and for loops to traverse arrays
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
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!