ForEach array traversal methods

Iterate

Through the array, all elements in the array are taken out.

Performed using a for loop array index (length-1) the same number of times.

var arr=["1", "5", "10", "25", "40", "1000"];
for(var i=0;i<arr.length;i++){
    console.log(arr[i]);
}

 

In addition to the common use for loop to go through the array, JS also provides a way for us to iterate forEach () 

  1, forEach () only supports IE8 and above browser.

  2, forEach () requires a function as a parameter, like this function, created by us but we could not help calling. Called callback function

There are several elements in the array, the function will be performed several times;

Each execution, the browser will traverse the elements to pass in the form of argument, we can define the parameter to read the content .

There are three elements of the array arr, so the function is executed three times.

var ARR = [ "snow", "snow", "frost" ]
arr.forEach(function(){
    console.log(11);
})

The browser will pass the callback function takes three arguments:

The first argument is currently being traversed element ;

The second argument, currently traversing the index of the element ;

The third parameter is iterated array ;

var ARR = [ "snow", "snow", "frost" ]
arr.forEach(function(aa,bb,cc,dd){
    console.log('aa='+aa+' ;bb='+bb+' ;cc='+cc+' ;dd='+dd);
})

forEach () This method only supports more than IE8 browser, IE and the browser do not support this method, so if IE8 compatible, do not use the forEach method, or use a for loop.

 

Guess you like

Origin www.cnblogs.com/nyw1983/p/11953699.html