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

How to use JS: functional array.forEach

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

Share

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

This article is about how to use JS: functional array.forEach, the editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article.

Overview of array.forEach () syntax

The forEach () method executes the given function once on each element of the array.

Const array1 = ['a', 'baked,' c']; array1.forEach (element = > console.log (element)); / / expected output: "a" / / expected output: "b" / / expected output: "c" parameter

Callback

The function executed for each element in the array, which takes one to three parameters:

-the current element being processed in the currentValue array.

-index the index of the current element being processed in the optional array.

-array the array that the optional forEach () method is operating on.

ThisArg optional parameters. When the callback function callback is executed, it is used as the value of this.

Return value

Undefined .

Array.forEach () description

The forEach () method executes the callback function once for each item in the array that contains valid values, and items that have been deleted or uninitialized are skipped (for example, on sparse arrays).

You can pass three parameters to the callback function in turn:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

The value of the current item of the array

The index of the current item of the array

The array object itself

If the thisArg parameter has a value, this points to the thisArg parameter each time the callback function is called. If the thisArg parameter is omitted, or if its value is null or undefined,this, it points to the global object. According to the common rule that the function observes this, the callback function can finally observe the this value.

The scope of the forEach () traversal is determined before the first call to callback. Items added to the array after calling forEach are not accessed by callback. If the existing value is changed, the value passed to callback is the value that forEach () traverses to their moment. Deleted items are not traversed to. If visited elements are deleted during iteration (for example, using shift ()), subsequent elements are skipped-- see the example below.

ForEach () executes the callback function once for each array element; unlike map () or reduce (), it always returns a undefined value and cannot be chained. A typical use case is the side effect of the last execution of a call chain (side effects, functional programming, in which the function performs operations other than the returned result value).

When forEach () is called, it does not change the original array, that is, the array in which it is called (although the callback function may change the original array when called). (this may not be clear enough, refer to the EMCA language specification: 'forEach does not directly mutate the object on which it is called but the object may be mutated by the calls to callback function.', that is, forEach does not directly change the object that calls it, but that object may be changed by the callback function.)

Note: there is no way to stop or jump out of the forEach () loop other than throwing an exception. If you need to stop or jump out of the loop, the forEach () method is not the right tool to use.

If you need to terminate the loop early, you can use:

A simple for loop

For...of / for...in cycle

Array.prototype.every ()

Array.prototype.some ()

Array.prototype.find ()

Array.prototype.findIndex ()

These array methods can determine whether you need to continue traversing the array elements:

Every ()

Some ()

Find ()

FindIndex ()

As long as the conditions permit, you can also use filter () to filter out the parts that need to be traversed in advance, and then use forEach () to process.

Case 01 does nothing with uninitialized values (sparse array)

As you can see, the empty array units between 3 and 7 are not called by forEach () to the callback function, or do anything else.

Const arraySparse = [1Jing 3 console.log 7]; let numCallbackRuns = 0; arraySparse.forEach (function (element) {console.log (element); numCallbackRuns++;}); console.log ("numCallbackRuns:", numCallbackRuns); / / 1 / / 3 / 7 / / numCallbackRuns: 3 case 02 converts the for loop to forEachconst items = ['item1',' item2', 'item3']; const copy = []; / / before for (let item0) I {if (Array.isArray (I)) result.push (... flatten (I); else result.push (I);}) return result;} / / Usage const problem = [1,2,3, [4,5, [6,7], 8,9]]; flatten (problem); / / [1,2,3,4,5,6,7,8,9] case 08 remarks on the use of promise or async functions

If you use the promise or async function as the callback parameter of similar methods such as forEach (), it is best to consider the resulting execution order, otherwise it is prone to errors.

Let ratings = [5,4,5]; let sum = 0; let sumFunction = async function (a, b) {return a + b;} ratings.forEach (async function (rating) {sum = await sumFunction (sum, rating);}) console.log (sum); / / Expected output: 14 / / Actual output: above is how to use JS: functional array.forEach, the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

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