Comparative JavaScript array traversal methods

Foreword

The method of JavaScript loop through a variety of development and has developed an array of different traversal methods that up and running faster, use different recycling methods in those scenes, will be compared below:

Various methods of array traversal

for Statement

Code:

var arr = [1,2,4,6] for(var i = 0, len = arr.length; i < len; i++){ console.log(arr[i]) } 复制代码

This is the standard cycle for the wording of the statement is the most traditional, but also support string, a variable i is defined as an index to track the location of access, len is the length of the array, condition is that i can not exceed len.

forEach Statement

forEachCALLBACK function method is performed for each element of the array once provided, is an array forEach method, can be used to apply a function on each element in an array, forEachfor the implementation of the callback function is only available for each array element array. traversing an array so that each element of the array to do one thing. those deleted (using the delete method, etc.) or uninitialized items will be skipped (but excluding those items of value undefined) (for example, the sparse array) ; unlike the map () or the reduce (), it always returns undefined value, and can not call chain. A typical use case is performed last in a chain of effects.

Code:

var arr = [1,5,8,9] arr.forEach(function(item) { console.log(item); }) 复制代码

for-in Statement

Typically use for-into traverse the object's properties, but the properties need enumerableto be read to. for-inLoop can be traversed only enumerated attribute. Commonly used to traverse the object, including the name and type of non-integer inherited properties above those of the prototype chain can also be traversed. Like Array and Object constructor using the built-created objects inherit properties from non-enumerable Object.prototype and String.prototype can not be traversed.

Code:

var obj = {
    name: 'test',
    color: 'red', day: 'sunday', number: 5 } for (var key in obj) { console.log(obj[key]) } 复制代码

for-of Statement (ES 6)

for-ofIn the iteration statement creates objects (including Array, Map, Set, String, TypedArray, arguments objects, etc.) iteration of a loop, call a custom iteration hook, and the value of the statement is executed for each different attributes. As long as a iterable object, you can by for-ofiteration.

Code:

var arr = [{name:'bb'},5,'test'] for (item of arr) { console.log(item) } 复制代码

for-ofAnd for-inthe difference between

for-inIteration statement object to the original insertion order enumerable property. for-inWill inherit the properties of the object will traverse the chain again, it will take more time.

for-of Iteration statement only through the data object can be.

Other recycling method

map Method (without changing the original array)

mapMethods will give the original of each element in the array in order to call a callback function. each callback return value after execution (including undefined) combined to form a new array. callback function will be called on the index has value; those who had never been assigned a value or use delete to delete the index will not be called. Let array generates a new array by some calculations, alluding to a new array,

Code:

var arr = [1,2,3]
var firearr = arr.map(current => current * 5) 复制代码

reduce method

Let antecedent and items in the array to do some calculations and the final cumulative value,

Code:

var wallets = [4,7.8,3]
var totalMoney = wallets.reduce( function (countedMoney, wallet) { return countedMoney + wallet.money; }, 0) 复制代码

filter Method (without changing the original array)

filterCallback function is called once for each element of the array, and the use of such callback returns true or equivalent to the elements of all true values ​​to create a new array. callback is invoked only in the index has been assigned, for those who have been deleted or has never been assigned the index will not be called. Those elements not tested by the callback will be skipped and will not be included in the new array. Screened to filter out the array of eligible entries, to form a new array.

Code:

var arr = [2,3,4,5,6] var morearr = arr.filter(function (number) { return number > 3 }) 复制代码

every method

Method every array each element performs a callback function, so until it finds a callback returns false (represented may be converted to the Boolean value false) elements. If you find one such element, every method will return false immediately. Otherwise, callback returns true for every element, every will return true. Each entry in the array to detect eligibility, and if each of which meet the conditions, it will return true, otherwise returns false, a bit like a loop through the array and the operation callback. Only call for the index that have been assigned. It does not call for those indexes are deleted or was never assigned.

Code:

var arr = [1,2,3,4,5] var result = arr.every(function (item, index) { return item > 0 }) 复制代码

some method

some of the array elements each perform a callback function, such that until a callback returns a "true value" (the value can be converted to a Boolean value of true). If you find such a value, some will return true immediately. Otherwise, some returns false. callback is invoked only in those index "has value", does not call on those indexes are deleted or never been assigned. Are there some items in the array symbol condition check, if there is a will return true, otherwise returns false, a bit like through the array or operation.

Code:

var arr = [1,2,3,4,5] var result = arr.some(function (item,index) { return item > 3 }) 复制代码

Contrast traverse speed

Here I used the comparison jsPerf platform for testing.

JavaScritp loop comparison

I created two arrays are compared, why should this difference does it make, because of the different types of arrays javascript stored in the memory address format is not the same, when traversing the editor noted in calculating the length of the array element type, for example, if the array which are all of the Number class, circulate contains Number, String, Object hybrid array faster than the inside, it creates two arrays, a wholly undefined array, it is a hybrid array.

// 一个是空数组
var nullarr = new Array(10000) // [undefined,undefined,...undefined] // 另一个带不同类型的数据的数组 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] 复制代码

After testing found that a bit strange retrieved directly empty array will still slower than the data array Why is this strange? For comparison cycle of consistency I only choose among the array with data dataarrfor testing.

Then we compare the for for len forEach for-in for-of map filterspeed of circulation

 

image

 

You can see forthe speed of the cycle is the fastest, is the oldest cycling, but also to optimize the best, followed by for-ofthe new cycle is es6 was very easy to use, is the slowest for-inwe can make a few speed sorting

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

This time it is clear that a large number of processing cycles of data or to use the old forcycle efficiency is best, but do not do not use for-in, in fact, often have to be based on the actual scene, for-inmore used to traverse above object properties, for-inbut also in the process of traversal will traverse the inheritance chain, so that's why it efficiency is relatively slow, such maprate is not high, but the array processing to achieve the above functions very easy to use convenient Es6, alluding to easily create a new array. or, for example, use Iterator property is also the line, so every cycles have the right to use place.

everyAnd someincomplete method for operating a part of an array

everyAnd someare returned directly to the entire array determines the condition Boolean types. everySpeeds than somemuch faster.

image

 

Dry

Figure shows a JavaScript array method

 

image

 

At last

Finally different browser kernel I believe there will be little difference, interested friends can go to test, have any questions please leave a message to the blogger.

Attach test address

Further reading

  1. Iterator (iterator) Address
  2. Several ways JS array traversal performance analysis and comparison of address
  3. How to explain the difference between the image of the JavaScript map, foreach, reduce? address
  4. For-each over an array in JavaScript? 地址
  5. JavaScript for cycling performance comparison address

Author: ClarenceC
link: https: //juejin.im/post/5a3a59e7518825698e72376b
Source: Nuggets
copyright reserved by the authors. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.

 

Guess you like

Origin www.cnblogs.com/jianxian/p/12667593.html