JavaScript summarizes the basics by iterating through various loops

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 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 '); Will not execute a
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);
The $ (this) in $.each of Object {value:4, Writable:false, Enumerable:false, configurable:false}
is different from this, but the traversal results are the same, you Can be printed out in 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 be alarmed, and don't think he's too tall for birds.

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

() (),!function () {} () +function () {} () Three functions are executed in the way ^_^

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.