Look at a piece of code first
1 <!DOCTYPE HTML>2 <HTMLLang= "en">3 <Head>4 <MetaCharSet= "UTF-8">5 <title>Document</title>6 </Head>7 <Body>8 9 <Script>Ten //an ordinary array One vararr=[3,5,2,6]; A //normal for loop traversal - for(varI= 0; I<arr.length; I++){ - Console.log (i,"Type:"+typeofi,arr[i]); the } - //To iterate over an array with for - for(varkincharr) { - Console.log (k,"Type:"+typeofk,arr[k]); + } - </Script> + </Body> A </HTML>
This code shows a bit of the difference between A for loop traversal array and a for-in loop through an array:
The standard for-loop i is the number type, which represents the subscript of the array, but I in the Foreach loop represents the array's key is the string type.
It's not a pit, it's just a little different.
Look at the code again.
1 <!DOCTYPE HTML>2 <HTMLLang= "en">3 <Head>4 <MetaCharSet= "UTF-8">5 <title>Document</title>6 </Head>7 <Body>8 9 <Script>Ten //an ordinary array One vararr=[3,5,2,6]; A //extending a method on the array prototype - Array.prototype.extend= function(){ - Console.log ("extending a method in an array prototype"); the } - //normal for loop traversal - for(varI= 0; I<arr.length; I++){ - Console.log (i,"Type:"+typeofi,arr[i]); + } - //To iterate over an array with for + for(varkincharr) { A Console.log (k,"Type:"+typeofk,arr[k]); at } - </Script> - </Body> - </HTML>
This code is on the top of the code, based on the array to do a bit of expansion. Very simple, just add a function. But let's see what happens with the run:
The result of the output, there is a row, this line is our extension of a function, not our definition in the array of values. That's the problem.
In summary, with for...in ... In general, it does work correctly.
But if we are using foreach to iterate through an array in the project, let's say that one day he's not careful to extend the JS native array class, or introduce an external JS framework that extends the native array. That's the problem.
So it's best to iterate through the array with a For loop
It is best not to iterate through the array in JavaScript