JavaScript summarizes the various ways in which loops are traversed

  • 2020-10-23 20:00:08
  • OfStack

For the sake of the example, the existing array and json objects are shown below


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


for in

for(var item in arr|obj){} can be used to iterate over groups and objects

When traversing through groups, item represents the index value and arr represents the element corresponding to the current index value arr[item]
When traversing the object, item represents key value and arr represents value value corresponding to key value obj[item]


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

Regarding for in, the following points need to be noted:

In both the for and for in loops, the i value is retained after the end of the loop. So avoid using function self-execution.
Using return, break, continue to break out of the loop is the same as for loop 1, but with return it is important to note that in the body of the function, return indicates that the function has terminated and that even the code outside the loop does not continue to execute. break, on the other hand, simply terminates the loop and the rest of the code continues 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'); // Do not perform 
}
forEach

demoArr.forEach(function(arg) {})

The parameter arg represents each element of the array, as shown below


demoArr.forEach(function(e) {
  if (e == 'CSS3') {
    return; //  The loop is skipped 
    // break;  //  An error 
    // continue;//  An error 
  };
  console.log(e);
})

There are specific points to pay attention to below

forEach cannot traverse the object forEach cannot be used in IE. firefox and chrome implement this method forEach cannot use break, continue is out of loop, using return has the same effect as using continue1 in for loop

do/while

The way this function works is as follows, but one thing to note is that when using continue, if you put i++ after it, the value of i++ will not change until you end up in an endless loop. Therefore, do/while1 should be used with caution.

do/while is not recommended for iterating through groups


//  Direct use of while
(function() {
  var i = 0,
    len = demoArr.length;
  while(i < len) {
    if (i == 2) {
      // return; //  The function execution is terminated 
      // break; //  The loop is terminated 
      // continue; //  The loop will be skipped because the following code will not execute, i The value of theta does not change, so the loop will 1 It's stuck right here. Be careful!! 
    };
    console.log('demoArr['+ i +']:' + demoArr[i]);
    i ++;
  }
  console.log('------------------------');
})();

// do while
(function() {
  var i = 0,
    len = demo3Arr.length;
  do {
    if (i == 2) {
      break; //  The loop is terminated 
    };
    console.log('demo2Arr['+ i +']:' + demo3Arr[i]);
    i++;
  } while(i<len);
})();
$.each

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

You can iterate through groups and objects, where e represents the index value or key value, and ele represents the value value


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

The output is


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

There's a lot to watch out for here

Use return or return true to skip one loop and continue the next loop Use return false to terminate the loop's execution, but not the function's execution break and continue cannot be used to skip the loop

The this value output in the loop looks like this


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

console.log(this == ele);
// true

For the this value above, traverse 1


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

// 0 c
// 1 s
// 2 s
// 4 3

Why didn't length and [[PrimitiveValue]] traverse it? The answer was found in javascript Advanced Programming, which basically means that in the internal properties of javascript, Enumerable in the object data properties is set to false


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

It is dedicated to traversing DOMList


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

i: Sequence value ele: Only DOM elements that are currently traversed
this elements currently traversed by DOM cannot call the jQuery method
$(this) == $(ele) the jquery object that is currently traversing the element. You can call the jquery method to perform the dom operation
Use for in to traverse DOMList

Because domList is not an array, it's an object, just because its key value is 0,1,2... It feels like an array, but the result of the direct traversal is as follows


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

So when we use for in to traverse domList, we need to convert domList to an array


var res = [].slice.call(domList);
for(var item in res) {}

Objects like this also have the properties of the function arguments object, of course strings can be traversed, but because the other properties of the string enumerable is set to false, the result of traversal is the same as the array, so do not worry about this problem.
Small complement

If you find someone writing a function like this, don't panic, and don't think he's too big for his shoes


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

() (),! function() {}() +function() {}() three ways of function self-execution ^_^


Related articles: