Look at a piece of code first
1 <! DOCTYPE html> 2 }16 //use for in to traverse the array for (var. k in arr) { console.log (k, "type:" +typeof k,arr[k]); }20 </script>21 </body>22
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
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