If you want to traverse, except for loop , What else do you know ?——JavaScript All kinds of traversal ways

This is a question from an interview , At that time, I used the fashionable words to say , The whole person is ignorant , I said in a daze , I just seem to know for Circulation . Later, I returned to my mind , There are many , It's just for Loops are the most common , People often can't react to other things . Here is a summary of what I have learned and what I have found on the Internet . Hope to help yourself and the people you see .

For convenience , Existing arrays and json Object as follows :

 var demoArr = ['Javascript', 'Gulp', 'CSS3', 'Grunt', 'jQuery', 'angular'];
var demoObj = {
aaa: 'Javascript',
bbb: 'Gulp',
ccc: 'CSS3',
ddd: 'Grunt',
eee: 'jQuery',
fff: 'angular'
};

1. for sentence

for Statement is the most commonly used loop statement .

 (function() {
for(var i=0, len=demoArr.length; i<len; i++) {
if (i == 2) {
// return; // Function execution terminated
// break; // The cycle is terminated
continue; // The loop is skipped
};
console.log('demo1Arr['+ i +']:' + demo1Arr[i]);
}
})();

About for loop , There are several points to note :

  1. for In the loop i At the end of the loop, it still exists in the scope , because ECMAScript There is no block level scope in , Even if i Is a variable defined inside the loop , But it's still accessible outside the loop (JavaScript Advanced programming P57). So to avoid affecting other variables in the scope , Use function self execution to isolate it ()();
  2. Avoid using for(var i=0; i<demo1Arr.length; i++){} The way , The length of such an array is calculated every time , Less efficient than the way above . You can also put variable declarations in for In front of , Improve the readability ;

     var i = 0, len = demo1Arr.length;
    for(; i<len; i++) {};
  3. There are several ways to jump out of the loop
    • return Function execution terminated
    • break The cycle is terminated , Exit the current loop
    • continue The loop is skipped , That is, exit the current cycle , So let's go to the next loop

2. for-in sentence

for(var item in arr|obj){} Can be used to traverse arrays and objects

  • When traversing an array ,item Indicates the index value , arr Represents the element corresponding to the current index value arr[item]
  • When traversing objects ,item Express key value ,arr Express key Value corresponding value value obj[item]

 (function() {
for(var i in demoArr) {
if (i == 2) {
return; // Function execution terminated
// break; // The cycle is terminated
// continue; // The loop is skipped
};
console.log('demoArr['+ i +']:' + demoArr[i]);
}
console.log('-------------');
})();

About for in, There are several points to note :

  • stay for Circulation and for in In circulation ,i All values are retained at the end of the loop . So use function self execution to avoid .
  • Use return,break,continue Jumping out of the loop is all about for The cycle is consistent , But about return We need to pay attention to , In the body of a function ,return Express Function execution terminated , Even the code outside the loop , And I'm not going to go on . and break It's just End cycle , The following code will continue to execute .

     function res() {
    var demoArr = ['Javascript', 'Gulp', 'CSS3', 'Grunt', 'jQuery', 'angular']; for(var item in demoArr) {
    if (item == 2) {
    return;
    };
    console.log(item, demoArr[item]);
    }
    console.log('desc', 'function res'); // Not execute

3. forEach

demoArr.forEach(function(arg) {})

Parameters arg The element representing each item in the array , Examples are as follows :

 demoArr.forEach(function(val, index) {
if (e == 'CSS3') {
return; // The loop is skipped
// break; // Report errors
// continue;// Report errors
};
console.log(val, index);
})

About forEach, There are several points to note :

  • There is... In the callback function 2 Parameters , Represent values and indexes, respectively , This is related to jQuery Medium $.each contrary
  • forEach Can't traverse object
  • forEach Cannot be in IE Use in ,firefox and chrome This method is realized
  • forEach Can't use break,continue Out of the loop , Use return when , Effect and in for Use in loop continue Agreement
  • The most important point , You can add a second parameter , Is an array , And in the callback function this Will point to this array . And if there's no second parameter , be this Will point to window.

     var newArr = [];
    demoArr.forEach(function(val, index) {
    this.push(val); // there this Point to newArr
    }, newArr) 

    Although in the original forEach There are many limitations to the cycle , But the need to know him is , Many third-party libraries will extend his methods , So that it can be applied in many places , such as angular In the tool method of , Also have forEach Method , Its use is basically the same as the original one , It's just that there are no limitations , Can be in IE Next use , You can also traverse objects

     var result = [];
    angular.forEach(demoArr, function(val, index) {
    this.push(val);
    }, result); 

4. do/while

The specific implementation of the function is as follows , But it's worth noting that , When using continue when , If you will i++ It's in the back , that i++ The value of will never change , In the end, it's a dead cycle . Therefore use do/while Be careful .

Not recommended do/while The way to traverse the array

 // Use it directly while
(function() {
var i = 0,
len = demoArr.length;
while(i < len) {
if (i == 2) {
// return; // Function execution terminated
// break; // The cycle is terminated
// continue; // The loop will be skipped , Because the following code can't be executed ,i The value of , So the loop is stuck here all the time , Use with caution !!
};
console.log('demoArr['+ i +']:' + demoArr[i]);
i ++;
}
console.log('------------------------');
})(); // do while
(function() {
var i = 0,
len = demo3Arr.length;
do {
if (i == 2) {
break; // The cycle is terminated
};
console.log('demo2Arr['+ i +']:' + demo3Arr[i]);
i++;
} while(i<len);
})();

5. $.each

 $.each(demoArr|demoObj, function(e, ele))

Can be used to traverse arrays and objects , among e Represents an index value or key value ,ele Express value value .

 $.each(demoArr, function(e, ele) {
console.log(e, ele);
})

// Output is

 0 "Javascript"
1 "Gulp"
2 "CSS3"
3 "Grunt"
4 "jQuery"
5 "angular"

About $.each, There are several points to note :

  • Use return perhaps return true To skip a loop , Continue with the following loop
  • Use return false To terminate the execution of the loop , But it doesn't terminate function execution
  • Can't use break And continue To skip the loop
  • In circulation this The value output looks like this

     console.log(this);
    //String {0: "C", 1: "S", 2: "S", 3: "3", length: 4, [[PrimitiveValue]]: "CSS3"} console.log(this == ele);
    // true 

    About the above this value , Traverse the

     $.each(this, function(e, ele) {
    console.log(e, ele);
    }) // 0 c
    // 1 s
    // 2 s
    // 4 3

    Why? length and [[PrimitiveValue]] No traversal ? A sudden inspiration , stay 《javascript Advanced programming 》 Found the answer , It means javascript In the internal properties of , Put... In the object data attribute Enumerable Set up in order to false

     // see length The internal properties of 
    console.log(Object.getOwnPropertyDescriptor(this, 'length'));
    // Object {value: 4, writable: false, enumerable: false, configurable: false}
     

    $.each Medium $(this) And this Somewhat different , But the traversal result is the same , You can print it out in the test code .

6. $(selecter).each

Dedicated to traversing DOMList

 $('.list li').each(function(i, ele) {
console.log(i, ele);
// console.log(this == ele); // true
$(this).html(i);
if ($(this).attr('data-item') == 'do') {
$(this).html('data-item: do');
};
})
  • i: Sequence value ele: Only the currently traversed DOM Elements
  • this Currently traversed DOM Elements , Cannot call jQuery Method
  • $(this) == $(ele) Of the currently traversed element jquery object , You can call jquery Method dom operation

If you want to traverse, except for loop , What else do you know ?——JavaScript Various traversal methods of more related articles

  1. Binary tree ( Before the order , Middle preface , In the following order , sequence ) Traversing recursion and loop python Realization

    Binary tree traversal is a common project in the interview . For the traversal of the front, middle and back sequences of binary trees , Each traversal can be implemented by recursion and loop , And the recursive implementation of each traversal is simpler than the loop implementation . Here is a summary . One . In the sequence traversal There are three traversal methods in front, middle and back order ...

  2. C# Retain 2 A summary of several scenarios The cursor traverses all the databases and circulates to modify the database sql command Native js A case study of roulette lottery ( Lucky draw ) javascript Medium typeof And type judgment

    C# Retain 2 A summary of several scenarios   scene 1: C# Retain 2 Decimal place ,.ToString("f2") It can , But if the number is three decimal places, for example 1.253, Then after transformation, it will become 1.2 ...

  3. 【Javascript】JS Three ways to traverse arrays :map、forEach、filter

    Preface recently , Because of the project , Will often traverse the array at the front end . Handle ,JS There are many kinds of traversal methods , Often without attention , It may lead to confusion of knowledge , And there are some pits . The front end time is ediary It is concluded that js Native ...

  4. Get the maximum and minimum values of a numeric array , Use traversal to get each value , And then the way to record the maximum and minimum values .( Array traversal nesting if Judgment statement )

    package com.Summer_0420.cn; /** * @author Summer * . Gets the maximum value of a numeric array . minimum value * Method : Traverse to get every value , Record the maximum : * Method : Traverse to get every ...

  5. .map(function(item)...) This is by hashcode Automatic traversal , How can I traverse in the order I want ?

    The above is my front-end traversal code . my item There's one on name Field of , They are business license , Tax registration certificate and business license , How can I set the function to traverse in this order every time , instead of item The order that comes with it ? .map(func ...

  6. Yifangyun ( By phone or qq Communication is not enough , It's easy to forget, but it can't be repeated , The best way is to specify a platform , People on the team regularly review the latest records )

    author : City year link :http://www.zhihu.com/question/20579359/answer/106319200 source : It's up to the author to own the copyright , Please contact the author for permission to reprint . to update , After the text is sent out , good ...

  7. Iterators and for-of loop By the way Es5 Medium .map Traverse

    let set = new Set(); //set Method to remove duplicate data [1, 2, 3, 4, 2, 8, 4].map(function (elem) { set.add(elem); // End of traversal ...

  8. sqlserver Loop traversal in ( Ordinary loops and cursor loops )

    sql It's often used in cycles , Let's talk about normal loops and cursor loops 1. First you need a test table data Student

  9. python utilize for..in Traverse ,while Several modes of loop nesting compiling multiplication table

    Application for....in... Traversing the multiplication table in four directions : The lower left corner : import sysfor i in range(1,10): for j in range(1,i+1): sys.stdout. ...

Random recommendation

  1. .Net Use system.Security.Cryptography.RNGCryptoServiceProvider Class and System.Random Class to generate random numbers

    .Net We usually use Random Class to generate random numbers , In some scenarios , I found out Random The generated random numbers are unreliable , In the following example, we randomly generate 10 A random number : ; i < ; i++) { Rando ...

  2. YY Take a look at the scene of wechat offline payment

    It was mentioned in the last article that < The realization principle of inter-bank clearing >, This time, let's analyze the scene and process of offline payment . I saw an article today :http://www.huxiu.com/article/23248/1.html? ...

  3. ios-uitableviewcell an

    #import <UIKit/UIKit.h> @interface ZSDHelpCell : UITableViewCell @property (weak, nonatomic) I ...

  4. Metadata Lock principle 6

      One brief introduction    Last article <MetaData Lock One of >   A brief introduction to MySQL introduce MDL The cause and effect of , This article explores MDL The implementation principle and operation mechanism of . Two MDL The type of   meta ...

  5. Give Way footer Fixed on page ( viewport ) Bottom (CSS-Sticky-Footer)

    Give Way footer Fixed on page ( viewport ) Bottom (CSS-Sticky-Footer) It's a website for footer Fixed in browser ( When the page content is less than the height of the browser )/ Tips at the bottom of the page . from HTML and CSS Realization , There's nothing annoying h ...

  6. keil in code、data、idata The difference between

    Memory type Ben C51 Compiler support 8051 And its derived types 8051 All of the memory space of the variable with the memory type listed in the following table can be assigned to a specific memory space . Memory type describe code Program space 64 Kby ...

  7. jQuery Tool functions

    1. String manipulation <!DOCTYPE html> <html> <head lang="en"> <meta charset="U ...

  8. CoreText Simple Use

    - (void)drawRect:(CGRect)rect { NSString *longText = @"CoreText"; /* ... */ NSRange rang = ...

  9. 【 Share 】SAS Statistical analysis software learning course ebook Collection Download

    SAS It's a famous statistical analysis software , Its full name is Statistics Analysis System, First compiled by two graduate students in Biostatistics at the University of North Carolina , And in 1976 Established in SAS Institute of Software , Officially launched SAS Software . turn ...

  10. mysql8 Operation command ( Continuous updating )

    mysql Service management View service status systemctl status mysqld.service Start the service systemctl start mysqld.service Close the service systemctl ...