Detailed description of javascript traversal methods, detailed description of javascript

Source: Internet
Author: User

Detailed description of javascript traversal methods, detailed description of javascript

For the convenience of examples, the existing arrays and json objects are as follows:

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 directly look at the example. It's easy to use too much.

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

Note the following points about the for Loop:

  • The I in the for loop does not exist in the scope after the loop ends. To avoid affecting other variables in the scope, use the function self-execution method to isolate it ()();
  • Avoid using the for (var I = 0; I <demo1Arr. length; I ++) {} method. Such an array length is calculated every time, and the efficiency is lower than the above method. You can also put the variable declaration in front of the for statement to improve readability.
var i = 0, len = demo1Arr.length;for(; i<len; i++) {};
  • There are several methods to jump out of the loop:

Return function execution terminated
The break cycle is terminated.
The continue loop is skipped.
Complete instance

For in

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

  • When traversing an array, item indicates the index value, and arr indicates the element arr [item] corresponding to the current index value.
  • When traversing an object, item indicates the key value, and arr indicates the value corresponding to the key value. obj [item]
(Function () {for (var I in demoArr) {if (I = 2) {return; // function execution is terminated // break; // The loop is terminated // continue; // The loop is skipped}; console. log ('demoarr ['+ I +']: '+ demoArr [I]);} console. log ('-------------');})();

For in, pay attention to the following points:

  • In the for loop and for in loop, the I value is retained after the loop ends. Therefore, you can avoid using function self-execution.
  • Use return, break, and continue to exit the loop is consistent with the for loop. However, in the return function body, return indicates that the function execution is terminated, even if it is code outside the loop, or continue to execute. Break only terminates the loop, and the subsequent code will continue to be executed.
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 executed}

ForEach

DemoArr. forEach (function (arg ){})
The arg parameter indicates the element of each item in the array. The example is as follows:

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

Note the following:

ForEach cannot traverse objects
ForEach cannot be used in IE. firefox and chrome implement this method.
ForEach cannot use break, and continue jumps out of the loop. when return is used, the effect is the same as when continue is used in the for loop.
Do/while

The specific implementation method of the function is as follows, but it is worth noting that when you use continue, if you put I ++ behind it, the I ++ value will never change, finally, it is in an endless loop. Therefore, be cautious when using do/while.

We do not recommend that you use do/while to traverse arrays.
// Directly use the 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 code behind it cannot be executed and the I value has not changed, so the loop will remain stuck here, so use it 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 loop is terminated}; console. log ('demo2arr ['+ I +']: '+ demo3Arr [I]); I ++ ;}while (I <len );})();

$. Each

$. Each (demoArr | demoObj, function (e, ele ))
It can be used to traverse arrays and objects. e indicates the index value or key value, and ele indicates the 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 are many things to be aware.

  • Use return or return true to skip a loop and continue executing the subsequent Loop
  • If return false is used, the execution of the loop is terminated, but the function execution is not terminated.
  • You cannot use break or continue to skip a loop.
  • The output of this value in a loop is similar to the following:

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

For the above this value, traverse it.

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

Why is the length and [[PrimitiveValue] Not traversed? Suddenly, I found the answer in "javascript advanced programming", which means that the Enumerable in the object data attribute is set to false in the internal property of javascript.

// View the internal property console of length. log (Object. getOwnPropertyDescriptor (this, 'length'); // Object {value: 4, writable: false, enumerable: false, retriable: false}

$ (This) in $. each is different from this, but the traversal result is the same. You can print it out in the test code.
$ (Selecter). each

Used to traverse 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 is the currently traversed DOM element and cannot call the jQuery method.
  • $ (This) = $ (ele) jquery object of the element currently traversed. You can call jquery to perform dom operations.

Use for in to traverse DOMList

Because domList is not an array but an object, it just feels similar to the array because its key value is 0, 1, 2... but the result of direct traversal is as follows:

var domList = document.getElementsByClassName('its');for(var item in domList) { console.log(item, ':' + domList[item]);}// 0: <li></li>// 1: <li></li>// ...// length: 5// item: function item() {}// namedItem: function namedItem() {}

Therefore, 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) {}

Such an object also has the function attribute arguments object. Of course, the string can be traversed, but the enumerable of other attributes of the string is set to false, therefore, the traversal result is the same as the array, so you don't have to worry about this problem.
Small supplement

If you find that some people write functions like this, don't panic or think that they are too tall.

+function(ROOT, Struct, undefined) { ... }(window, function() { function Person() {}})

()(),! Function () {}() + function () {}() self-execution methods.

The above is all the content of this article, hoping to help you learn.

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.