Follow me to learn JavaScript for loops and for...in loops _javascript tips

Source: Internet
Author: User
Tags hasownproperty

As you know, there are two ways to iterate objects in javascript:

    • For loop;
    • For.. in circulation;

One, for loop

Insufficient:

The length of the array is to be obtained at each cycle;
The termination condition must be clear;
In the For loop, you can iterate over the values of an array or an array of similar objects, such as arguments and Htmlcollection objects. The usual cycle forms are as follows:

Second best loop for
(var i = 0; i < myarray.length i++) {
 //use Myarray[i] do something
}

The disadvantage of this form of circulation is that the length of the array is to be obtained each time the loop is cycled. This reduces the performance of your code, especially when MyArray is not an array, but a Htmlcollection object.

Htmlcollections refers to the object returned by the DOM method, for example:

Document.getelementsbyname ()
Document.getelementsbyclassname ()
document.getElementsByTagName ()

There are other htmlcollections, which were introduced before the DOM Standard and are still in use. Yes:

Document.images: All the picture elements on the page
Document.links: all a tag elements
Document.forms: All Forms
Document.forms[0].elements: All fields on the first form on the page

The trouble with collections is that they are querying basic documents (HTML pages) in real time. This means that every time you access the length of any collection, you have to query the DOM in real time, and DOM operations are generally expensive.

That's why when you loop through the values, the length of the cached Array (or collection) is a better form, as shown in the following code:

for (var i = 0, max = myarray.length i < max i++) {
 //using myarray[i] do something
}

In this way, you retrieve only one length value during this cycle.

In all browsers, the length of the cached htmlcollections is faster, twice times (SAFARI3) to 190 times times (IE7), when the content is recycled. This data looks very old

Note that when you explicitly want to modify the collection in the loop (for example, by adding more DOM elements), you may prefer length updates to constants.

With the single var form, you can move the variable from the loop, as follows:

function Looper () {
 var i = 0,
  max,
  myarray = [];
 // ...
 for (i = 0, max = Myarray.length i < max; i++) {
  //using myarray[i] do something
 }
}

This form has the advantage of consistency because you stick to the single var form. The problem is that it's difficult to copy and paste the entire loop when you refactor the code. For example, you copy a loop from one function to another, and you have to make sure that you can introduce I and max into a new function (if it doesn't work here, it's very likely that you'll have to delete them from the original function).

The last one that needs to be adjusted for loops is to replace i++ with one of the following expressions.

i = i + 1
i = 1

JSLint prompts you to do this because + + and –-promote "overly tricky (excessive trickiness)". If you ignore it directly, the jslint plusplus option will be false (default defaults).

Two types of change:

    • One less variable (no max)
    • Down to 0, usually faster, because comparing to 0 is more effective than the number of arrays or other things that are not 0.01
The first form of change:

var i, myarray = [];
for (i = myarray.length; i–-;) {
 ///use Myarray[i] do something
}

//second use while loop:

var myarray = [],
 i = myarray.length;
while (i–-) {
 //use Myarray[i] do something
}

These small improvements are only reflected in performance, and JSLint will complain about the use of i–-.

For ... in loops-also known as "enumerations"

For ... in loops are often used to iterate over an object's properties or each element of an array, and the loop counter in the for...in loop is a string, not a number. that contains the name of the current property or the index of the current array element. Here are just a few examples:

When traversing an object, the variable i, the loop counter, is the property name of the object:

Use for.. In loop Traversal object Properties 
varperson={ 
 Name: "Admin", 
 age:21, address 
 : "Shandong" 
}; 
for (var i in person) { 
 console.log (i); 
} 

The results of the execution are:

Name

Age

Address

When traversing an array, the variable i, the loop counter, is the index of the current array element:

Use for.. In loop traversal array 
vararray = ["admin", "manager", "DB"] for 
(Vari in array) { 
 console.log (i); 
} 

Execution results:

0

1

2

But now it appears for. The in loop is pretty good, but don't be too happy to take a look at the following example:

var array =["admin", "manager", "DB"; 
Add a name attribute to the Array's prototype 
array.prototype.name= "Zhangsan"; 
for (var i in array) { 
 alert (array[i]); 
} 

Run Result:

Admin

Manager

Db

Zhangsan
Gee, wonders, how come out of nowhere for a Zhangsan
Now, what about using the For loop?

Vararray = ["admin", "manager", "DB"]; 
Add a name attribute to the Array's prototype 
Array.prototype.name = "Zhangsan"; 
for (var i =0; i<array.length; i++) { 
 alert (array[i]); 
 

Run Result:

Admin

Manager

Db
Oh, now I see, for. The in loop loops through the methods and attributes in a type of prototype (prototype), so this can cause unexpected errors in your code. To avoid this problem, we can use the hasOwnProperty () method of the object to avoid this problem, and the hasOwnProperty () method returns True if the object's properties or methods are inheritable. That is, the check here does not involve properties and methods inherited from other objects, only the properties that are created directly in the specific object itself.

Vararray = ["admin", "manager", "DB"]; 
Array.prototype.name= "Zhangshan"; 
for (var i in array) { 
//If it is not a property created directly by the object itself (that is, the genus//sex is a property in the prototype), skip the display 
 if (Array.hasownproperty (i)) { 
  alert ( Array[i]); 
  }
 

Run Result:

Admin

Manager

DB
Another form of using hasOwnProperty () is to cancel the method on the Object.prototype. Like this:

Object
var man = {
 hands:2,
 legs:2,
 heads:1
};
for (var i in mans) {
 if (Object.prototype.hasOwnProperty.call (man, i)) {//filter
  Console.log (i, ":", Man[i]);
 }
}

The benefit is to avoid naming conflicts in cases where the man object is redefined hasownproperty. Also avoids all the methods of long attribute lookup objects, you can "cache" it using local variables.

var i, Hasown = Object.prototype.hasOwnProperty;
For (I in Mans) {
 if (Hasown.call (man, i)) {//filter
  Console.log (i, ":", Man[i]);
 }

Strictly speaking, not using hasOwnProperty () is not a mistake. Depending on the task and how confident you are with the code, you can skip it to increase the speed of the loop. But when you're unsure about the current object's content (and its prototype chain), adding hasOwnProperty () is more insurance.

A formatted change (jslint) simply ignores the curly braces and places the IF statement on the same line. The advantage is that the loop statement reads like a complete idea (each element has one of its own attribute "X", using "X" to do Something):

Warning: Pass JSLint detection
var i, hasown = Object.prototype.hasOwnProperty;
For (I in Mans) if (Hasown.call (man, i)) {//filter
 Console.log (i, ":", Man[i]);
}

The above is an introduction to the two ways that JavaScript provides iterative objects: for loops and for...in loops, and hopefully this article will help you learn.

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.