Js uses the for loop to traverse the Array

Source: Internet
Author: User

Js uses the for loop to traverse the Array

Today I wrote something boring! For Loop usage! The following code defines array a and array B as a pseudo array!

var a = [1,2,3,0,5,4];var b = document.getElementsByTagName('li'); //[
  • 1
  • ,
  • 2
  • ,
  • 3
  • ,
  • 4
  • ,
  • 5
  • ]

     
    

    First: incorrect type!
    For (var I = 0; I <. length; I ++) {// This writing method is the most basic, but the error is that the array length should not be obtained every time, So we usually use the second Writing Method !}

    Type 2: General type!
    For (var I = 0, l =. length; I <l; I ++) {// This writing method is the most common, better understood, and also common. For the two types of a and B (pseudo) all arrays are supported .}

    Type 3: optimized
    For (var I = a. length-1; I> = 0; I --) {// This write method is clever, traversing in reverse order, thus saving a temporary variable! For both a and B (pseudo) arrays. // Google compiler compression will optimize the for loop !}


    Fourth: Special settings
    For (var I = 0; B [I]; I ++) {// This writing method is not generic, and it won't work for Array! But it is very practical for the collection of dom elements such as array B !}


    Fifth: Skill
    For (var I = 0, elem; (elem = B [I])! = Null; I ++) {// This method is also used in specific situations. When the element of the array is not equal to a certain value, here, the loop is stopped when null or undefined is encountered, so array a can also be used! // The trick is to assign values while declaring conditions! This reduces the code for assigning temporary variables to a row !}


    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.