1. for...in is used to iterate over an enumerable property of an array or an object's properties. Note that the enumerable properties of the object from the prototype chain are also looped. See below for an example
var arr = ["Lee", "Hello", "Zhangsan"];
for (var i in arr) {
Console.log (Arr[i]);//lee Hello Zhangsan
}
Arrays are also objects that can add their own properties we add a Name property to Arr
Arr.name = "Anne Baby"
for (var i in arr) {
Console.log (Arr[i]);//lee Hello Zhangsan Anne Baby
}
So how do you understand that the enumerable properties of the object from the prototype chain will also be looped? Look at the following example
var bar = {A:1,b:2,c:3};
function foo () {
This.color = "Red";
}
Foo.prototype = bar;
var obj = new Foo ();
For (var prop in obj) {
Console.log ("O.") +prop+ "=" +obj[prop])//o.color = Red o.a = 1 o.b =2 o.c = 3
}
The last example copy code run a look at the results
<ul id= "box" >
<li class= "Child" >1</li>
<li class= "Child" >2</li>
<li class= "Child" >3</li>
<li class= "Child" >4</li>
</ul>
<script>
var ul = document.queryselector ("#box");
var li = Ul.queryselectorall (". Child");
For (var i in Li) {
Console.log (Li[i]);
Li[i].onclick = function () {
alert ("Hello")
}
}
</script>
2.forEach is a method of manipulating arrays in ES5, and the main function is to iterate through an array directly to see an example
var arr = ["Zhangsan", "Lisi", "Wangwu"];
arr.name = "SDFSDFSDF"; Arr.foreach (function(element) { Console.log (Element)//Zhangsan Lisi Wangwu })
A brief analysis of several traversal methods in JavaScript