Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the methods of JavaScript loop traversal

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the methods of JavaScript cycle traversal, which has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to know about it.

Preface

Those loop traversal methods in JavaScript:

I. Array traversal method

1. ForEach ()

The forEach method invokes each element of the array and passes the element to the callback function. Each value in the array calls a callback function. The syntax is as follows:

Array.forEach (function (currentValue, index, arr), thisValue)

The first parameter of this method is a callback function, which is required, and it has three parameters:

CurrentValue: required. Current element

Index: optional. The index value of the current element.

Arr: optional. The array object to which the current element belongs

Let arr = [1 console.log 2 3 arr 4] arr.forEach ((item, index, arr) = > {console.log (index+ ":" + item)})

This method can also have a second argument to bind the this variable inside the callback function (provided that the callback function cannot be an arrow function because the arrow function does not have a this):

Let arr = [1, index, 3, 4, 5] let arr1 = [9, 8, 7, 6, 5] arr.forEach (function (item, index, arr) {console.log (item) / 9 8 7 65}, arr1)

Note:

The forEach method does not change the original array, nor does it return a value

ForEach cannot use break,continue to jump out of the loop, and the effect of using return is the same as using continue in the for loop

The forEach method cannot traverse an object and is only suitable for traversing arrays.

2. Map ()

The map () method returns a new array whose elements are the values of the original array element after calling the function. This method processes the elements in turn in the order of the original array elements. The syntax is as follows:

Array.map (function (currentValue,index,arr), thisValue)

The first parameter of this method is a callback function, which is required, and it has three parameters:

CurrentValue: yes. Value of the current element

Index: optional. The index value of the current element

Arr: optional. The array object to which the current element belongs.

Let arr = [1,2,3]; arr.map (item = > {return item + 1;}) / / output result: [2,3,4]

The second parameter of this method is used to bind the this variable inside the parameter function, which is optional:

Let arr = ['await,' baked,'c']; [1,2] .map (function (e) {return this [e];}, arr) / / output result: ['baked,' c']

This method can also make chained calls:

Let arr = [1,2,3]; arr.map (item = > item + 1) .map (item = > item + 1) / / output result: [3,4,5]

Note:

The map method does not detect empty arrays

When the map method traverses the array, it returns a new array without changing the original array.

The map method has a return value, which can be return. Return is supported in the callback function of map.

The map method cannot traverse an object and is only suitable for traversing arrays.

3. For of

The for...of statement creates a loop to iterate over iterating objects. The for...of loop introduced in ES6 to replace for...in and forEach () and supports the new iterative protocol. The syntax is as follows:

For (variable of iterable) {statement}

This method has two parameters:

Variable: the attribute values for each iteration are assigned to this variable.

Iterable: an object that has enumerable properties and can be iterated.

This method allows you to get the key value of an object:

Let arr = [{id:1, value:'hello'}, {id:2, value:'world'}, {id:3, value:'JavaScript'}] for (let item in arr) {console.log (item);} / / output result: 0 1 2

Note:

The for of method only iterates through the properties of the current object, not on its prototype chain.

The for of method is suitable for traversing arrays / class arrays / strings / map/set and other collections with iterator objects

The for of method does not support traversing normal objects because it does not have an iterator object. If you want to traverse the properties of an object, you can use the for in method

You can use break, continue, and return to break the loop traversal

4. Filter ()

The filter () method is used to filter the array, and elements that meet the criteria are returned. Its argument is a callback function, which is executed by all array elements in turn. Elements that return true are returned, and empty arrays are returned if there are no qualified elements. The syntax is as follows:

Array.filter (function (currentValue,index,arr), thisValue)

The first parameter of this method is a callback function, which is required, and it has three parameters:

CurrentValue: yes. Value of the current element

Index: optional. The index value of the current element

Arr: optional. The array object to which the current element belongs.

Const arr = [1,2,3,4,5] arr.filter (item = > item > 2) / / output result: [3,4,5]

Similarly, it has a second parameter, which is used to bind the this variable inside the parameter function.

You can use the filter () method to remove undefined, null, NAN and so on from the array:

Let arr = [1, undefined, 2, null, 3, false,', 4,0] arr.filter (Boolean) / / output result: [1,2,3,4]

Note:

The filter method returns a new array without changing the original array.

The filter method does not detect empty arrays

The filter method applies only to detection arrays.

5. Some (), every ()

The some () method iterates through each item in the array, returns true as long as one element meets the criteria, and the remaining elements are no longer detected, otherwise it returns false.

The every () method iterates through each item in the array and returns true only if all elements meet the criteria. If an element is detected in the array that does not satisfy, the entire expression returns false, and the remaining elements are no longer detected. The syntax is as follows:

The syntax of the two is as follows:

Array.some (function (currentValue,index,arr), thisValue) array.every (function (currentValue,index,arr), thisValue)

The first parameter of the two methods is a callback function, which is required, and it has three parameters:

CurrentValue: yes. Value of the current element

Index: optional. The index value of the current element

Arr: optional. The array object to which the current element belongs.

Let arr = [1,2,3,4,5] arr.some (item = > item > 4) / / output result: truelet arr = [1,2,3,4,5] arr.every (item = > item > 0) / / output result: true

Note:

Neither method changes the original array and returns a Boolean value

Neither method detects an empty array.

Both methods apply only to detection arrays.

6. Reduce (), reduceRight ()

The reduce () method takes a function as an accumulator, and each value in the array (from left to right) starts to shrink and eventually evaluates to a value. Reduce () can be used as a higher-order function for the compose of a function. The syntax is as follows:

Array.reduce (total, currentValue, currentIndex, arr), initialValue)

The reduce method executes the callback function for each element of the array in turn, excluding the elements in the array that have been deleted or have never been assigned, and the callback function accepts four parameters:

Total: the value returned by the last callback, or the initial value provided (initialValue)

CurrentValue: the element currently being processed

CurrentIndex: the index of the current element

Arr: the array object to which the current element belongs.

The second argument to this method is initialValue, which represents the initial value passed to the function (as the first argument to call callback for the first time):

Let arr = [1,2,3,4] let sum = arr.reduce ((prev, cur, index, arr) = > {console.log (prev, cur, index); return prev + cur;}) console.log (arr, sum)

Output result:

1 2 1

3 3 2

6 4 3

[1, 2, 3, 4] 10

Let's add an initial value:

Let arr = [1,2,3,4] let sum = arr.reduce ((prev, cur, index, arr) = > {console.log (prev, cur, index); return prev + cur;}, 5) console.log (arr, sum)

Output result:

5 1 0

6 2 1

8 3 2

11 4 3

[1, 2, 3, 4] 15

It can be concluded that if no initial value is provided, initialValue,reduce will execute the callback method at index 1, skipping the first index. If the initial value initialValue is provided, execute from index 0

The use of the reduceRight () method is almost the same as that of reduce (), except that this method traverses the array in reverse order, while the reduce () method traverses the positive order.

Let arr = [1,2,3,4] let sum = arr.reduceRight ((prev, cur, index, arr) = > {console.log (prev, cur, index); return prev + cur;}, 5) console.log (arr, sum)

Output result:

5 4 3

9 3 2

12 2 1

14 1 0

[1, 2, 3, 4] 15

Note:

Neither method will change the original array

If the two methods add an initial value, they will change the original array and place the initial value in the last bit of the array

The two methods do not perform callback functions for empty arrays.

7. Find (), findIndex ()

The find () method returns the value of the first element of the array judged within the function. When the element in the array returns true when the condition is tested, find () returns the element that meets the condition, and the subsequent value does not call the execution function. Returns undefined if there are no eligible elements.

The findIndex () method returns the position (index) of the first element of the array in which a test function is passed in. When an element in the array returns true under a function condition, findIndex () returns the index position of the element that meets the condition, and the subsequent value does not call the execution function. Returns-1 if no eligible element is returned.

The syntax of the two methods is as follows:

Array.find (currentValue, index, arr), thisValue) array.findIndex (function (currentValue, index, arr), thisValue)

The first parameter of the two methods is a callback function, which is required, and it has three parameters:

CurrentValue: required. Current element

Index: optional. Index of the current element

Arr: optional. The array object to which the current element belongs.

Let arr = [1,2,3,4,5] arr.find (item = > item > 2) / / output result: 3let arr = [1,2,3,4,5] arr.findIndex (item = > item > 2) / / output result: 2

The find () and findIndex () methods are almost the same, but the results are different:

Find (): returns the first qualified value

FindIndex: returns the index value of the value of the first return condition.

Note:

Two methods for empty arrays, functions are not executed

The two methods do not change the original array.

8. Keys (), values (), entries ()

All three methods return an array of iterative objects with different contents:

Keys () returns the index value of the array

Values () returns the elements of the array

Entries () returns the key-value pair of the array.

The syntax of the three methods is as follows:

Array.keys () array.values () array.entries ()

None of these three methods has parameters:

Let arr = ["Banana", "Orange", "Apple", "Mango"]; const iterator1 = arr.keys (); const iterator2 = arr.values () const iterator3 = arr.entries () for (let item of iterator1) {console.log (item);} / / output result: 0 12 3for (let item of iterator2) {console.log (item);} / / output result: Banana Orange Apple Mangofor (let item of iterator3) {console.log (item) } / / output result: [0, 'Banana'] [1,' Orange'] [2, 'Apple'] [3,' Mango']

Summary:

Method whether to change the characteristics of the original array forEach () No return value map () No return value can be chained call for of No for...of to traverse the properties of the object with Iterator iterator, return the element of the array, the attribute value of the object, cannot traverse the ordinary obj object, turn the asynchronous loop into a synchronous loop filter () No filter array, return the array containing qualified elements Chainable calls to every (), some () No some () return true as long as one of them is true While every () returns false.find () as long as one is false, findIndex () No find () returns the first qualified value; findIndex () returns the index value of the first returned condition value reduce (), reduceRight () No reduce () positive array operation; reduceRight () reverse array operation keys (), values (), entries () No keys () returns the index value of the array; values () returns the array element. Entries () returns the key-value pair of the array. Second, object traversal method

1. For in

For... In is mainly used to loop object properties. Each time the code in the loop executes, it operates on the properties of the object. The syntax is as follows:

For (var in object) {

Block of code executed

}

Two of these parameters:

Var: yes. The specified variable can be an array element or a property of an object.

Object: yes. Specifies the object for the iteration.

Var obj = {a: 1, b: 2, c: 3}; for (var i in obj) {console.log ('key name:', I); console.log ('key value:', obj [I]);}

Output result:

Key name: a

Key value: 1

Key name: B

Key value: 2

Key name: C

Key value: 3

Note:

The for in method iterates not only through all the enumerable properties of the current object, but also through the properties on its prototype chain.

2. Object.keys (), Object.values (), Object.entries ()

All three methods are used to traverse an object, and it returns an array of its own enumerable attributes of a given object (excluding inherited and Symbol attributes). The array elements are arranged in the same order as when traversing the object in a normal loop, and the values returned by these three elements are as follows:

Object.keys (): returns an array of object key names

Object.values (): returns an array containing object key values

Object.entries (): returns an array of object key names and key values.

Let obj = {id: 1, name: 'hello', age: 18}; console.log (Object.keys (obj)); / / output result: [' id', 'name',' age'] console.log (Object.values (obj)); / / output result: [1, 'hello', 18] console.log (Object.keys (obj)) / / output result: [['id', 1], [' name', 'hello'], [' age', 18]

Be careful

The values in the array returned by the Object.keys () method are all strings, which means that key values that are not strings are converted to strings.

The attribute values in the resulting array are all enumerable properties of the object itself, excluding inherited properties.

3. Object.getOwnPropertyNames ()

The Object.getOwnPropertyNames () method, similar to Object.keys (), takes an object as a parameter and returns an array containing all the property names of the object itself. But it can return properties that cannot be enumerated.

Let a = ['Hello',' World']; Object.keys (a) / / ["0", "1"] Object.getOwnPropertyNames (a) / / ["0", "1", "length"]

Both methods can be used to calculate the number of attributes in an object:

Var obj = {0: "a", 1: "b", 2: "c"}; Object.getOwnPropertyNames (obj) / / ["0", "1", "2"] Object.keys (obj). Length / / 3Object.getOwnPropertyNames (obj). Length / / 34. Object.getOwnPropertySymbols ()

The Object.getOwnPropertySymbols () method returns an array of Symbol attributes of the object itself, excluding string attributes:

Let obj = {a: 1} / / add a Symbol attribute Object.defineProperties (obj, {[Symbol ('baz')]: {value:' Symbol baz') that cannot be enumerated to the object Enumerable: false}}) / / add an enumerable Symbol attribute to the object obj [Symbol ('foo')] =' Symbol foo' Object.getOwnPropertySymbols (obj). ForEach ((key) = > {console.log (objkey)}) / / output result: Symbol baz Symbol foo5. Reflect.ownKeys ()

Reflect.ownKeys () returns an array containing all the properties of the object itself. It is similar to Object.keys (), where Object.keys () returns the property key, but does not include properties that cannot be enumerated, while Reflect.ownKeys () returns all properties key:

Var obj = {a: 1, b: 2} Object.defineProperty (obj, 'method', {value: function () {alert ("Non enumerable property")}, enumerable: false}) console.log (Object.keys (obj)) / / ["a", "b"] console.log (Reflect.ownKeys (obj)) / / ["a", "b", "method"]

Note:

Object.keys (): equivalent to returning an array of object attributes

Reflect.ownKeys (): equivalent to Object.getOwnPropertyNames (obj) .concat (Object.getOwnPropertySymbols (obj).

Summary:

Object method traversal basic property traversal prototype chain traversal non-enumerable attribute traversal Symbolfor in whether No Object.keys () No Object.getOwnPropertyNames () whether Object.getOwnPropertySymbols () No Reflect.ownKeys () third, other traversal methods

1. For

The for loop should be the most common way to loop. It consists of three expressions, namely, declaring loop variables, judging loop conditions, and updating loop variables. The three expressions are separated by semicolons. You can use temporary variables to cache the length of the array to avoid repeatedly getting the length of the array, and the optimization effect will be more obvious when the array is larger.

Const arr = [1, let 2, 3, 4, 5] for (len I = 0, len = arr.length; I)

< len; i++ ){ console.log(arr[i])} 在执行的时候,会先判断执行条件,再执行。for循环可以用来遍历数组,字符串,类数组,DOM节点等。可以改变原数组。 2. while while循环中的结束条件可以是各种类型,但是最终都会转为布尔值,转换规则如下。 Boolean:true为真,false为假; String:空字符串为假,所有非空字符串为真; Number:0为假,非0数字为真; null/Undefined/NaN:全为假; Object:全为真。 let num = 1; while (num < 10){ console.log(num); num ++;} while和for一样,都是先判断,再执行。只要指定条件为 true,循环就可以一直执行代码。 3. do / while 该方法会先执行再判断,即使初始条件不成立,do/while循环也至少会执行一次。 let num = 10; do { console.log(num); num--; }while(num >

= 0); console.log (num); / /-1

It is not recommended to use do / while to traverse arrays.

4. For await of

The for await...of method is called an asynchronous iterator, and it is mainly used to traverse asynchronous objects. It is a method introduced in ES2018.

The for await...of statement creates an iterative loop over asynchronous or synchronous iterable objects, including String,Array, class arrays, Map, Set, and custom asynchronous or synchronous iterable objects. This statement can only be used within async function:

Function Gen (time) {return new Promise ((resolve,reject) = > {setTimeout (function () {resolve (time)}, time)} async function test () {let arr = [Gen (2000), Gen (3000), Gen (3000)] for await (let item of arr) {console.log (Date.now (), item)}} test ()

Output result:

Thank you for reading this article carefully. I hope the article "what are the methods of traversing the JavaScript cycle" shared by the editor will be helpful to you. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report