Ways to iterate over an array

Source: Internet
Author: User

1. for () {}

var arr = [1,2,3,4,5];for (let i=0; i<arr.length; i++) {  //...  }

Cons: Code But concise

2. ForEach ()

var arr = [1,2,3,4,5];arr.foreach (function (value,index) {    //...});

Disadvantage: Cannot interrupt stop the entire loop

3, for...in

var arr = [1,2,3,4,5];for (Let me in arr.) {  //...  }

Note: for...in loops are more commonly used for "object" loops, and if you are using loops for "arrays", the I that gets in each loop is "string type" rather than the expected number type, which is the first type conversion to be performed.

4, For...of

var arr = [1,2,3,4,5];for (let value of arr) {  console.log (value);//1 2 3 4 5   }

Note: The ① is more concise than the For loop, ② can use break to terminate the entire loop, or continue to jump out of the loop, continue to the back loop, ③ combine keys () to get the index of the loop, and the number type, not the string type.

* Cycle can be terminated

var arr = [1,2,3,4,5];for (let value of arr) {  if (value = = 3) {break     ;     }    Console.log (value);  } Printed results: 1 2

* Skip the current loop

var arr = [1,2,3,4,5];for (let value of arr) {  if (value = = 3) {      continue;    }    Console.log (value);  } Printed results: 1 2 4 5

* Get index of number type

var arr = [1,2,3,4,5];for (Let Index of Arr.keys ()) {  console.log (index);  } Printed results: 0 1 2 3 4

  

Ways to iterate over an array

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.