Detailed JavaScript traversal method _javascript Skills

Source: Internet
Author: User
Tags terminates

For illustrative purposes, 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 see the example directly, it's too much, it's simple.

(function () {
 for (var i=0, len=demoarr.length; i<len; i++) {
 if (i = = 2) {
 //return;//function execution terminated
 // Break The loop is terminated
 continue;//loops are skipped
 };
 Console.log (' demo1arr[' + i + ']: ' + demo1arr[i]);
 }
();
For the For loop, there are a few

For a For loop, there are several points to note

    • I in the For loop still exists after the end of the loop and in the scope, in order to avoid affecting other variables in the scope, use the function itself to isolate () ();
    • Avoid using for (Var i=0 i<demo1arr.length; i++) {} so that the length of the array is computed every time, less efficient than the way it was above. You can also perform a variable declaration in front of for to improve reading
var i = 0, len = demo1arr.length;
for (; i<len; i++) {};
    • There are several ways to jump out of the loop

The return function execution is terminated
Break loop is terminated
The continue loop is skipped.
Full Instance

For in

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

    • When traversing an array, item represents an index value, arr represents the element corresponding to the current index value Arr[item]
    • When traversing an object, item represents a key value, arr represents the value corresponding to the key value Obj[item]
(function () {for
 (var i in Demoarr) {
 if (i = = 2) {return
 ;//function execution terminated
 //break;//Loop terminated
 //CONT Inue; Loops are skipped
 };
 Console.log (' demoarr[' + i + ']: ' + demoarr[i]);
 }
 Console.log ('-------------');
} ();

There are several things to note about in:

    • In the For loop and in loop, the I value is preserved after the loop ends. So you avoid using functions that you perform themselves.
    • The use of return,break,continue out loops is consistent with the For loop, but in return you need to be aware that in the body of the function, return means that the function execution terminates, even if the code outside the loop does not continue. The break only terminates the loop, and the following code continues to execute.
function res () {
 var demoarr = [' Javascript ', ' Gulp ', ' CSS3 ', ' grunt ', ' jQuery ', ' angular '];

 for (var item = Demoarr) {
 if (item = 2) {return
 ;
 };
 Console.log (item, Demoarr[item]);
 Console.log (' desc ', ' function res '); does not execute
}

Foreach

Demoarr.foreach (function (ARG) {})
parameter arg represents an element of each item in an array, with the following instance

Demoarr.foreach (function (e) {
 if (e = = ' CSS3 ') {return
 ;//Loops skipped
 //break;//Error
 //continue;//error 
   };
 Console.log (e);
})

There are the following areas to be noted specifically

foreach cannot traverse object
foreach cannot be used in IE, Firefox and Chrome implement this method
foreach cannot use break,continue to jump out of loops, and when using return, the effect is consistent with the continue used in the For loop
Do/while

The specific implementation of the function is as follows, but it is noteworthy that when using continue, if you put the i++ in the back, then the i++ value will not change, and eventually into a dead loop. So use do/while must be careful.

It is not recommended to traverse an array using the Do/while method
//Direct use while

(function () {
 var i = 0,
 len = demoarr.length;
 while (I < len) {
 if (i = = 2) {
 //return;///function execution terminated
 //break;//loop terminated//
 continue;//loop will be skipped because the following code has no The law executes, I the value does not change, therefore the cycle will always be stuck here, uses cautiously!!
 };
 Console.log (' demoarr[' + i + ']: ' + demoarr[i]);
 i + +;
 }
 Console.log ('------------------------');
} ();

Do
while (function () {
 var i = 0,
 len = demo3arr.length;
 Do {
 if (i = = 2) {break
 ;//loop terminated
 };
 Console.log (' demo2arr[' + i + ']: ' + demo3arr[i]);
 i++;
 } while (I<len);
}) ();

$.each

$.each (demoarr|demoobj, function (e, ele))
Can be used to traverse arrays and objects, where E represents an index value or a key value, and Ele represents a value

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

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 the loop once, and continue to follow the loop
    • Use return False to terminate the execution of the loop, but does not terminate the function execution
    • Cannot use break and continue to skip loops
    • The This value output in the 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

About the This value above, iterate over the

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

0 C
//1 s
//2 s
//4 3

Why does length and [[Primitivevalue]] not traverse out? A sudden flash, in the JavaScript advanced programming found the answer, presumably meaning that the internal properties of JavaScript, the object data properties in the enumerable set to False

View the internal properties of length
console.log (this, ' length ') (object.getownpropertydescriptor);
Object {value:4, Writable:false, Enumerable:false, Configurable:false}

The $ (this) in $.each is different from this, but the traversal results are the same, you can print out the test code to see
$ (selecter). each

Specifically 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: DOM elements that are currently traversed only
    • This is the DOM element that is currently being traversed and cannot invoke the jquery method
    • $ (this) = = $ (ele) A jquery object that is currently traversed by the element, and can invoke the JQuery method for DOM operations

Traversing domlist using for in

Because Domlist is not an array, it is an object simply because its key value is 0,1,2 ... And the feeling is similar to the array, but the result of the 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 () {}

So we need to convert domlist to an array when we iterate over domlist using for.

var res = [].slice.call (domlist);
For (var item in res) {}

Objects like this also have properties arguments objects of functions, and of course strings can be traversed, but because the enumerable of other properties of the string is set to false, the result of the traversal is the same as the array, without worrying about the problem.
Small Supplement

If you find that some people write functions like this, don't panic, and don't think he's tall.

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

() (), how!function () {} () +function () {} () three functions are executed.

The above is the entire content of this article, I hope to help you learn.

Related Article

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.