Learn the javascript for Loop and for... in loop _ javascript skills

Source: Internet
Author: User
Tags hasownproperty
I want to learn about the javascript for Loop and... in loops, which are objects that are iterated in JavaScript in two ways. This article will learn for loops and... if you are interested in the in loop, you will know that there are two methods to iterate objects in JavaScript:

  • For loop;
  • For... in loop;

I. for Loop


It is because the length of the array needs to be obtained during each loop;
The conditions for termination should be clear;
In a for loop, you can obtain the values of arrays or arrays similar to objects, such as arguments and HTMLCollection objects. The general cycle is as follows:

// The second best loop for (var I = 0; I <myarray. length; I ++) {// use myarray [I] To Do Something}

The disadvantage of this type of loop is that the length of the array needs to be obtained at each loop. This reduces your code performance, especially when myarray is not an array but an 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. Include:

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

The trouble with collections is that they query Basic Documents (HTML pages) in real time ). This means that every time you access the length of any set, you need to query the DOM in real time, and DOM operations are generally expensive.

This is why when you get the value cyclically, the length of the cached array (or set) is better, as shown in the following code:

For (var I = 0, max = myarray. length; I <max; I ++) {// What To Do With myarray [I}

In this way, you only retrieve the length value once in this loop.

In all browsers, the length of the cache HTMLCollections is faster when the content is obtained cyclically, between 2 times (Safari3) and 190 times (IE7. // The data looks very old

Note that when you explicitly want to modify the set in the loop (for example, adding more DOM elements), you may prefer length update instead of constants.

With the single var form, you can extract variables from the loop, as shown below:

Function logoff () {var I = 0, max, myarray = []; //... for (I = 0, max = myarray. length; I <max; I ++) {// use myarray [I] To Do Something }}

This form has the benefit of consistency because you stick to the single var form. The disadvantage is that it is difficult to copy and paste the entire loop when refactoring the code. For example, if you copy a loop from a function to another function, You have to determine that you can introduce I and max to a new function (if it is useless here, it is very likely that you will delete them from the original function ).

To adjust the loop, replace I ++ with one of the following expressions.

i = i + 1i += 1

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

Two forms of change:

  • One Variable missing (no max)
  • Counting down to 0 is usually faster, because comparing with 0 is more efficient than comparing with array length or something other than 0. 01

// The first form of change: var I, myarray = []; for (I = myarray. length; I --;) {// use myarray [I] To Do Something} // second use the while loop: var myarray = [], I = myarray. length; while (I --) {// use myarray [I] To Do Something}

These minor improvements are only reflected in performance, and JSLint will complain about using I.

II.... In loop-also known as "enumeration"

For... An in loop is often used to iterate the attributes of an object or every element of an array.... The cyclic counter in an in loop is a string rather than a number. It contains the name of the current attribute or the index of the current array element. The following are examples:

When traversing an object, the variable I, that is, the cyclic counter, is the property name of the object:

// Use .. in loop traversal Object Property varperson = {name: "Admin", age: 21, address: "shandong"}; for (var I in person) {console. log (I );}

The execution result is:




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

// Use for .. in to traverse array vararray = ["admin", "manager", "db"] for (vari in array) {console. log (I );}

Execution result:




However, it seems that the for... in loop is quite useful now, but don't be too happy. Let's take a look at the example below:

Var array = ["admin", "manager", "db"]; // Add a name attribute Array to the Array prototype. prototype. name = "zhangsan"; for (var I in array) {alert (array [I]);}

Running result:




Why is there a zangsan?
Now let's take a look at how the for loop works?

Vararray = ["admin", "manager", "db"]; // Add a name attribute Array to the Array prototype. prototype. name = "zhangsan"; for (var I = 0; I

Running result:



Oh, now I understand that the for... in loop will traverse the methods and attributes of a prototype, so this may lead to unexpected errors in the code. To avoid this problem, we can use the hasOwnProperty () method of the object to avoid this problem. If the attributes or methods of the object are not inherited, The hasOwnProperty () method returns true. That is, the check here does not involve attributes and methods inherited from other objects. It only checks attributes directly created in the specific object itself.

Vararray = ["admin", "manager", "db"]; Array. prototype. name = "zhangshan"; for (var I in array) {// if the property is not directly created by the object itself (that is, the property in the prototype ), if (array. hasOwnProperty (I) {alert (array [I]) ;}}

Running result:



Another way to use hasOwnProperty () is to cancel the method on Object. prototype. Like this:

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

The advantage is that the name conflict is avoided when the man object is redefined with hasOwnProperty. It also avoids all methods for searching objects with long attributes. You can use the local variable "cache" it.

Var I, hasOwn = Object. prototype. hasOwnProperty; for (I in man) {if (hasOwn. call (man, I) {// filter the console. log (I, ":", man [I]) ;}}

Strictly speaking, not using hasOwnProperty () is not an error. Based on the task and your confidence in the code, you can skip it to improve the speed of the loop. However, when you are not sure about the content of the current object (and its prototype chain), adding hasOwnProperty () is more secure.

Formatting changes (though JSLint) will directly ignore curly braces and place the if statement on the same line. The advantage is that loop statements read like a complete idea (each element has its own attribute "X" and what to do with "X ):

// Warning: JSLint cannot detect var I, hasOwn = Object. prototype. hasOwnProperty; for (I in man) if (hasOwn. call (man, I) {// filter the console. log (I, ":", man [I]);}

The above describes the two methods provided by JavaScript to iterate objects: for Loop and for... in loop. I hope this article will help you learn more.

Related Article

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.