Original article to fe2x.cc reprint please mark the original author and the attached original article link

preface

JavaScript has developed a variety of methods for looping through arrays. The different looping methods run faster than the others. The different looping methods are used in which scenarios.

Various array traversal methods

forstatements

Code:

var arr = [1.2.4.6]
for(var i = 0, len = arr.length; i < len; i++){
    console.log(arr[i])
}
Copy the code

This is the standard for loop and it’s the most traditional way to write it, and strings are also supported, so you define a variable I as an index to keep track of where you’re going, and len is the length of the array, as long as I can’t exceed len.

forEachstatements

The forEach method performs the supplied CALLBACK function once on each element of an array. ForEach is an array method that can be used to apply a function to each element of an array. The forEach CALLBACK function forEach element of an array can only be used for arrays. Iterating over an array causes each element of the array to do one thing. Items that have been deleted (using the delete method, etc.) or are not initialized will be skipped (but not those with a value of undefined) (for example on a sparse array); Unlike map() or reduce(), it always returns undefined and cannot be called chained. The typical use case is to perform side effects at the end of a chain.

Code:

var arr = [1.5.8.9]
arr.forEach(function(item) {
    console.log(item);
})
Copy the code

for-instatements

A for-In loop usually iterates through an object’s properties, but an attribute needs enumerable to be read. A for-in loop only iterates through an enumerable property. It is commonly used to iterate over objects, including names of non-integer types and properties above the inherited stereotype chain. Objects created using built-in constructors like Array and Object inherit the non-enumerable properties of Object.prototype and String.prototype and cannot be iterated.

Code:

var obj = {
    name: 'test'.color: 'red'.day: 'sunday'.number: 5
}
for (var key in obj) {
    console.log(obj[key])
}
Copy the code

for-ofStatement (ES)

The for-of statement creates an iteration loop over iterable objects (including Array, Map, Set, String, TypedArray, Arguments, and so on), calls custom iteration hooks, and executes statements for the values of each different property. As long as it is an iterable object, it can iterate through for-of.

Code:

var arr = [{name:'bb'},5.'test']
for (item of arr) {
    console.log(item)
}
Copy the code

for-offor-inThe difference between

The for-in statement iterates over the enumerable properties of an object in the original insertion order. For-in iterates through all the object properties of the inheritance chain, so it takes more time.

The for-of statement only iterates through the iterable’s data.

Other loop method

mapMethod (without changing the original array)

The map method calls the callback function once, in order, for each element in the array. The return values (including undefined) from each callback are combined to form a new array. Callback is called only on indexes that have values; Indexes that have never been assigned a value or deleted with delete are not called. Let’s take an array and do some calculation to generate a new array, map it to a new array,

Code:

var arr = [1.2.3]
var firearr = arr.map(current= > current * 5)
Copy the code

reducemethods

Let the front and the back of the array do some sort of calculation and add up the final value,

Code:

var wallets = [4.7.8.3]
var totalMoney = wallets.reduce( function (countedMoney, wallet) {
    return countedMoney + wallet.money;
}, 0)
Copy the code

filterMethod (without changing the original array)

Filter calls callback once for each element in the array and creates a new array with all elements that cause callback to return true or its equivalent. Callback will only be called on indexes that have been assigned, not indexes that have been deleted or never assigned. Elements that do not pass the callback test are skipped and not included in the new array. Filter out the items that meet the conditions in the array to form a new array.

Code:

var arr = [2.3.4.5.6]
var morearr = arr.filter(function (number) {
    return number > 3
})
Copy the code

everymethods

The every method executes the callback function once for each element in the array until it finds an element that causes the callback to return false (representing a value that can be converted to a Boolean value of false). If one is found, the every method will immediately return false. Otherwise, callback returns true for each element, and every returns true. Checks if each item in the array meets the criteria, and returns true if each item meets the criteria, false otherwise, a bit like iterating through the array and operating on the callback. Called only for indexes that have already been assigned a value. Not called for indexes that are deleted or never assigned.

Code:

var arr = [1.2.3.4.5]
var result = arr.every(function (item, index) {
    return item > 0
})
Copy the code

somemethods

Some performs a callback function once for each element in the array until a value is found that causes the callback to return a “true” value (which can be converted to a Boolean value true). If such a value is found, some will immediately return true. Otherwise, some returns false. Callback will only be called on indexes that “have a value”, not indexes that have been deleted or never assigned a value. Checks if there are any sign conditions for items in the array, returning true if there is one, false otherwise, a bit like iterating through arrays or operations.

Code:

var arr = [1.2.3.4.5]
var result = arr.some(function (item,index) {
    return item > 3
})
Copy the code

Compare the traversal speed

In contrast, I used the jsPerf platform for testing.

JavaScritp loop contrast

I created two arrays for comparison. Why do I want to make this difference? Because different types of arrays hold different address formats in javascript memory, the editor will take into account the length of the array element type Tring and Object are faster, so we created two arrays, one all-undefined and one mixed.

// One is an empty array
var nullarr = new Array(10000) // [undefined,undefined,...undefined]

// Another array with different types of data
var dataarr = []
for(var i = 0; i < 10000; i++){
    if (i % 2= = =0) {
        dataarr[i] = i.toString()
    } else {
        dataarr[i = i
    }
}
dataarr / / [1, '2', 3..., 10000]
Copy the code

It’s a little bit strange when you test it out that retrieving an empty array is still slower than retrieving a data array why is that strange? In order to compare the consistency of the loop, I only selected the dataarr array with the data.

Let’s compare the speed of the for for Len forEach for-in-for-of map filter loop

As you can see, the for loop is the fastest, it’s the oldest loop, and it’s the best optimized loop, followed by for-of which is a new loop on ES6 that’s very useful, and the slowest is for-in, so we can sort this by speed

for > for-of > forEach > filter > map > for-in

In fact, most of the time, the scene should be based on the actual situation. For-in is mostly used for traversing object attributes. In the process of traversing, for-In also traverses inheritance chains, so this is the reason why its efficiency is relatively slow. For example, the map speed is not high, but the processing is very easy to use in Es6 array function, easy to create new arrays. Or use Iterator attributes for example, so each loop has its place.

everysomeNot exactly an array manipulation method

Every and some are both methods that check the condition and return the entire array Boolean type directly. Every is much faster than some.

Dry goods

A diagram shows JavaScript array methods

The last

Finally, different browser kernel I believe there will be some differences, interested friends can go to test, any questions welcome to the blogger message.

Attach the address of the test

read

  1. Address of an iterator
  2. JS several array traversal methods and performance analysis address comparison
  3. How to visually explain the difference between Map, foreach, and Reduce in JavaScript? address
  4. For-each over an array in JavaScript? address
  5. JavaScript for loop performance comparison address