Here, we will look at the for of loop. This loop will allow us to loop through an array and perform some action for each element. Additionally, we will learn how to work with the Array.entries() method.
0:00 MDN for of loop
0:36 Setting up our array
1:40 Using the for of loop
2:51 Array.entries() method
5:30 Using the break statement
8:23 Using the for of loop inside of a function
Example #1:
const requiredSubjects = ["English", "Algebra", "History", "Chemistry", "Typing", "P.E.", "Computer Science"];
const extraCourses = ["Biology", "Trigonometry", "Spanish"];
const mySubjects = [...requiredSubjects, ...extraCourses];
Example #2:
const myNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
Example #3:
menuItems1 = [["Pizza", "$5"], ["Tacos", "$2"], ["Hamburger", "$4"], ["Sandwich", "$3"], ["Chicken", "$6"]];
menuItems2 = [["Steak", "$10"], ["Pasta", "$5"], ["Rice and Beans", "$1"], ["Eggs", "$2"], ["Ravioli", "$3"]];
menuItems3 = [["Chips", "$1"], ["Cookies", "$3"], ["Brownie", "$2"], ["Cake", "$6"], ["Ice Cream", "$4"]];
function getMenu (array) {
let myString = "";
for (const [index, [food, price]] of array.entries()) {
myString += `Item Number: ${index + 1}: ${food} for the price of ${price}.`;
if (index !== array.length - 1) {
myString += `\n`;
}
}
return myString;
}
JavaScript Playlist:
• JavaScript for Beginners
MDN for..of Loop:
https://developer.mozilla.org/en-US/d...
MDN Array.entries():
https://developer.mozilla.org/en-US/d...
NodeJS:
nodejs.org
VS Code:
code.visualstudio.com
Информация по комментариям в разработке