Detail javascript traversal method

  • 2020-10-31 21:37:10
  • 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

You can look directly at the example, too many, very simple


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

Here are a few things to note about the for loop

i in the for loop still exists in the scope after the end of the loop. In order to avoid affecting other variables in the scope, it is isolated by the way of function self-execution ()(); Avoid for(var i=0; i < demo1Arr.length; i++){}, where the array length is calculated each time, is less efficient than above. Variable declarations can also be executed before for to improve readability

var i = 0, len = demo1Arr.length;
for(; i<len; i++) {};
There are several ways to get out of the loop

The return function execution is terminated
The break loop is terminated
The continue loop is skipped
A complete instance

for in

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

When iterating 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 should be noted:

In both for loops 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 get 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, which is implemented by firefox and chrome
forEach cannot use break. continue breaks out of the loop. When using return, the effect is the same as using continue1 in the for loop
do/while

The function is implemented 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 infinite loop. So be careful with do/while1.

do/while is not recommended for traversing groups
// Use while directly


(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))
Can be used to iterate over groups and objects, where e represents the index value or key value and ele represents 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 with the next loop Use return false to terminate the loop's execution, but not the function's execution You cannot use break and continue 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 roughly means that javascript's internal properties are set to false in the object data properties


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

The $(this) in $.each is different from this, but the traversal results in one sample that you can print out in the test code
$(selecter).each

It's dedicated to traversing DOMList


(function() {
 for(var i=0, len=demoArr.length; i<len; i++) {
 if (i == 2) {
 // return; //  The function execution is terminated 
 // break; //  The loop is terminated 
 continue; //  The loop is skipped 
 };
 console.log('demo1Arr['+ i +']:' + demo1Arr[i]);
 }
})();
 about for Cycle, 1 The next few 
1 i: Sequence value ele: Only the DOM element that is currently traversed The DOM element currently traversed by this cannot call the jQuery method $(this) == $(ele) the jquery object that is currently traversing the element. You can call the jquery method for the dom operation

Use for in to traverse DOMList

Because domList is not an array, but 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=0, len=demoArr.length; i<len; i++) {
 if (i == 2) {
 // return; //  The function execution is terminated 
 // break; //  The loop is terminated 
 continue; //  The loop is skipped 
 };
 console.log('demo1Arr['+ i +']:' + demo1Arr[i]);
 }
})();
 about for Cycle, 1 The next few 
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 function property arguments object, of course the string can also be traversed, but because the other properties of the string enumerable is set to false, the traversal result will be 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 tall.


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

() (),! function() {}() +function() {}() three ways of self-executing functions.

Above is the entire content of this article, I hope to help you with your study.


Related articles: