A brief analysis of several traversal methods in JavaScript

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.