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 JavaScript Array.forEach () traverses the elements in the array

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly shows you "JavaScript Array.forEach () how to traverse the elements in the array", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "JavaScript Array.forEach () how to traverse the elements in the array" this article.

In JavaScript, you often need to traverse the array set and merge it into a callback method for each iteration. JS developers usually use a useful way to do this: the forEach () method.

The forEach () method calls the specified callback function once for each element it iterates through the array. Like other array iterators such as map and filter, the callback function can accept three parameters:

Current element: this is the item in the array that is currently being iterated.

Its index: this is the index position of the item in the array

Target array: this is the array being iterated

This forEach method does not return the new array sort like filter,map and other iterators. Instead, the method returns the undefined itself. So it's not as linkable as other methods.

The other thing about forEach is that you cannot terminate the loop (using the break statement) or make it skip an iteration (using the continue statement). In other words, you can't control it.

The only way to terminate the forEach loop is to throw an exception in the callback function. Don't worry, we'll see all of this in practice soon.

How to use methods in JavaScript with forEach ()

Imagine a group of students standing in line for a routine roll call. The class coordinator walks through the line and calls out the name of each student, marking whether they are present or not.

It should be noted that the coordinator does not change the order of students in the line. After finishing the roll call, he kept them on the same line. All he does is perform an operation on everyone (his examination).

In the following example, with this scenario in mind, we will see how to use the methods in forEachJavaScript to solve real-world problems.

The method example in forEach () JavaScript how to delete the first odd number forEach () in an array

In this example, we have an array that has an odd number in the first position, followed by several even numbers. But we only want the numbers in this array to be even. So we will use the forEach () loop to remove odd numbers from the array:

Let numbers = [3, 6, 8, 10, 12] let odd = 3 numbers forEach (function (number) {if (number = odd) {numbers.shift () / / 3 will be deleted from array}}) console.log (numbers); [6, 8, 10, 12] / / All even! How to access the index property forEach ()

In this example, we will execute a function for each student whose rollCall loops within the array. The rollcall function simply records the string associated with each student to the console.

Names = ["anna", "beth", "chris", "daniel", "ethan"] function rollCall (name, index) {console.log (`Is the number ${index + 1} student-${name} present? Yes! `);} names.forEach ((name, index) = > rollCall (name, index)); / * "Is the number 1 student-anna present? Yes!"Is the number 2 student-beth present? Yes!"Is the number 3 student-chris present? Yes!"Is the number 4 student-daniel present? Yes!"Is the number 5 student-ethan present? Yes!" * /

In this example, the only information we have about each student is their name. However, we also want to know what pronouns each student uses. In other words, we want to define a pronoun attribute for each student.

So we define each student as an object with two attributes, a name and a pronoun:

Names = [{name: "anna", pronoun: "she"}, {name: "beth", pronoun: "they"}, {name: "chris", pronoun: "he"}, {name: "daniel", pronoun: "he"}, {name: "ethan", pronoun: "he"}] function rollCall (student, index) {console.log (`The number ${index + 1} student is ${student.name}. Is ${student.pronoun} present? Yes! `);} names.forEach ((name, index) = > rollCall (name, index)); / * "The number 1 student is anna. Is she present? Yes!"The number 2 student is beth. Is they present? Yes!"The number 3 student is chris. Is he present? Yes!"The number 4 student is daniel. Is he present? Yes!"The number 5 student is ethan. Is he present? Yes!" * /

We record each student's roll call message to the console, then we perform a check to see the pronouns used by the students, and finally we dynamically pass the exact pronouns as part of the string.

How to use forEach () JavaScript to copy an array to a new array

After three years of study, it is time for every student to graduate. In our JavaScript, we define two arrays: stillStudent and nowGraduated. As you may have guessed, stillStudent catches students before they graduate.

The forEach loop then receives each student and calls the function on its graduateStudent.

In this function, we construct an object with two properties: the name of the student and the location where they graduated. Then we pass the new object to the nowGraduated array. By that time, the students had already graduated.

This example also demonstrates how to use the forEach () method to copy an array to a new array.

Let stillStudent = ["anna", "beth", "chris", "daniel", "ethan"] let nowGraduated = [] function graduateStudent (student, index) {let object = {name: student, position: index + 1} nowGraduated [index] = object} stillStudent.forEach ((name, index) = > graduateStudent (name, index); console.log (nowGraduated) / * [{name: "anna", position: 1}, {name: "beth", position: 2}, {name: "chris", position: 3}, {name: "daniel", position: 4}, {name: "ethan", position: 5}] * / how to use the array parameter to check the next item in the array

At some point, the teacher needs to check to see if there is the next specific item in the list. In this case, the teacher needs to have a broad understanding of the entire list. In this way, he can determine whether the next student needs to call.

In our JavaScript, we can copy this because the callback function can also access the array (third) parameter. This parameter represents the target array, namely name.

We check to see if there is the next item (student) in the array. If so, we pass the string positive to the nextItem variable. If not, we pass the string negative to the variable. Then for each iteration, we check to see if the student is really the last.

Names = ["anna", "beth", "chris", "daniel", "ethan"] function rollCall (name, index, array) {let nextItem = index + 1

< array.length ? "postive" : "negative" console.log(`Is the number ${index + 1} student - ${name} present? Yes!. Is there a next student? ${nextItem}!`);}names.forEach((name, index, array) =>

RollCall (name, index, array) / * "Is the number 1 student-anna present? Yes!. Is there a next student? Postive! "" Is the number 2 student-beth present? Yes!. Is there a next student? Postive! "" Is the number 3 student-chris present? Yes!. Is there a next student? Postive! "" Is the number 4 student-daniel present? Yes!. Is there a next student? Postive! "" Is the number 5 student-ethan present? Yes!. Is there a next student? Negative! "* / you can't exit the forEach loop, so use every () instead.

Remember when I mentioned that, in essence, you can't jump out of the forEach loop? Once started, it runs until it reaches the last item in the array. Therefore, if you insert a break statement, it will return a SyntaxError:

Let numbers = [2, 4, 5, 8, 12] let odd = 5 (function (number) {if (number = odd) {break; / / oops, this isn't gonna work!}})

In general, if you finally achieve what you want to achieve before you reach the last project, you will want to jump out of the loop. In the above example, we have found the odd number (5), so there is no need to iterate over the remaining projects (8 and 12).

If you want to jump out of the loop under certain circumstances, you must use any of the following methods:

For ring

For... Of or for... In cycle

Array.some ()

Array.every ()

Array.find ()

The following is the method Array.every () for how to jump out of the loop:

Let numbers = [2, 4, 5, 8, 12] let odd = 5 numbers every (number = > {if (number = = odd) {return false;} console.log (number); return true;}); / / 24 is all the content of the article "how to traverse the elements in the array". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to 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