Summary of JS array traversal method

Source: Internet
Author: User
Tags array length

Array Traversal method

1.for Cycle

With temporary variables, the length is cached to avoid repeated acquisition of the array length, and the optimization effect is more noticeable when the array is large.

for (j = 0,len=arr.length; J < Len; J + +) {   }

2.foreach Cycle

Iterate through each item in the array, no return value, no effect on the original array, ie not supported

1 No Return value Arr.foreach ((item,index,array) =>{    //Execute code})//parameter: The current item in the value array, index of the current item, array original array, or//array with several items, Then the anonymous callback function passed in will need to be executed several times;

3.map Cycle

With a return value, you can return it.

The return value is supported in the callback function of map, and what is returned is equivalent to what the item in the array is (it does not affect the original array, but is equivalent to cloning a copy of the original array, which changes the corresponding item in the array of the cloned copy);

Arr.map (function (value,index,array) {//do something return XXX})
var ary = [12,23,24,42,1];  var res = Ary.map (function (item,index,ary) {      return item*10;  })  Console.log (res);//-->[120,230,240,420,10];  The original array was copied and modified Console.log (ary);//-->[12,23,24,42,1]; the  original array has not changed

 

4.FOROF traversal

Can respond correctly to break, continue, and return statements

for (var value of MyArray) {Console.log (value);}

  

5.filter traversal

Does not change the original array, returns the new array

var arr = [  {id:1, text: ' AA ', done:true},  {id:2, text: ' BB ', Done:false}]console.log (Arr.filter (item => ; Item.done))

Switch to ES5

Arr.filter (function (item) {  return item.done;});
var arr = [73,84,56, 22,100]var NEWARR = arr.filter (item = item>80)   //Get new array [+] Console.log (Newarr,arr)

  

6.every traversal

Every () is a given function that runs for each item in the array, and returns True if the function returns true for each item.

var arr = [1, 2, 3, 4, 5, 6];  Console.log (Arr.every (item, index, array) {          return item > 3;})      );  False

 

7.some traversal

Some () is a specified function that runs on each item in an array, and returns True if the function returns true for either item.

var arr = [1, 2, 3, 4, 5, 6];        Console.log (Arr.some (item, index, array) {          return item > 3;})      );  True

  

8.reduce

reduce() Method receives a function as an accumulator (accumulator), and each value (from left to right) in the array begins to shrink, resulting in a value.

var total = [0,1,2,3,4].reduce ((A, b) =>a + B); 10

reduceAccept a function that has four parameters, namely: Last value, current value, index of current value, array

[0, 1, 2, 3, 4].reduce (function (Previousvalue, CurrentValue, index, array) {return previousvalue + currentvalue;});

reduceThere is a second parameter, we can use this parameter as callback the first parameter when the first call, the above example because there is no second argument, so directly from the array of the second item, if we give the second parameter is 5, then the result is this:

[0, 1, 2, 3, 4].reduce (function (Previousvalue, CurrentValue, index, array) {return previousvalue + currentvalue;},5);

 

The value of the first call is previousValue replaced with the second parameter passed in,

9.reduceRight

reduceRight()The functions and functions of the method are the same, but the array items in the array are added reduce() reduceRight() forward from the end of the array.

reduceRight()The first time a callback function callbackfn is called, prevValue and curValue can be one of two values. If reduceRight() a parameter is supplied when called initialValue , it is prevValue equal initialValue to, equal to, the curValue last value in the array. If no argument is supplied initialValue , it is prevValue equal to the last value of the array, curValue equal to the second-lowest value in the array.

var arr = [0,1,2,3,4];arr.reduceright (function (prevalue,curvalue,index,array) {    return prevalue + curvalue;});// 10

The callback will be called four times, and the parameters and return values of each call are as follows:

If you provide an initial value initialValue of 5 :

var arr = [0,1,2,3,4];arr.reduceright (function (prevalue,curvalue,index,array) {    return prevalue + Curvalue;}, 5); 15

The callback will be called five times, the parameters of each call and the values returned are as follows:

Similarly, you can add a sum to an array, or you can use the reduceRight() method:

var arr = [1,2,3,4,5,6];console.time ("Ruduceright"); Array.prototype.ruduceRightSum = function () {for    (var i = 0; i < 10000; i++) {        return  this.reduceright (fu Nction (Prevalue, curvalue) {            return prevalue + curvalue;        });}    } Arr.ruducerightsum (); Console.log (' final value: ' + arr.ruducesum ()); 21console.timeend ("Ruduceright"); 5.725ms

10.find

The Find () method returns the first element in the array that matches the condition of the test function. Otherwise, return undefined

var stu = [    {        name: ' Zhang San ',        Gender: ' Male ',        age:20    },    {        name: ' Wang Xiao ',        Gender: ' Male ', age        :    {        name: ' John Doe ',        Gender: ' Male ',        age:20    }]
function Getstu (Element) {   return element.name = = ' John Doe '}stu.find (getstu)//Return result is//{name: "John Doe", Gender: "Male", age:20}

ES6 method

Stu.find (Element) = (Element.name = = ' John Doe '))

11.findIndex

FindIndex   method invokes a callback function (in ascending index order) until an element returns &NBSP; True . As long as one element returns True, FindIndex   Returns the index value of the element that returns true immediately.

FindIndex does not change the array object.

[1,2,3].findindex (function (x) {x = = 2;}); /Returns An index value of 1.

12.keys,values,entries

ES6 provides three new methods for--entries (), keys (), and values ()--for iterating over an array. They all return a Walker object that can be traversed with the For...of loop, the only difference being that keys () is the traversal of the key name, values () is the traversal of the key value, and entries () is the traversal of the key-value pair

For (Let index of [' A ', ' B '].keys ()) {Console.log (index);} 0//1for (Let elem of [' A ', ' B '].values ()) {Console.log (elem);} ' A '//' B ' for (let [index, Elem] of [' A ', ' B '].entries ()) {Console.log (index, elem);} 0 "A"//1 "B"

  

Summary of JS array traversal method

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.