Javascript foreach двумерный массив

Array.prototype.forEach()

The forEach() method executes a provided function once for each array element.

Try it

Syntax

forEach(callbackFn) forEach(callbackFn, thisArg) 

Parameters

A function to execute for each element in the array. Its return value is discarded. The function is called with the following arguments:

The current element being processed in the array.

The index of the current element being processed in the array.

The array forEach() was called upon.

A value to use as this when executing callbackFn . See iterative methods.

Return value

Description

The forEach() method is an iterative method. It calls a provided callbackFn function once for each element in an array in ascending-index order. Unlike map() , forEach() always returns undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.

callbackFn is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

Читайте также:  Поменять цвет кнопки при нажатии css

forEach() does not mutate the array on which it is called, but the function provided as callbackFn can. Note, however, that the length of the array is saved before the first invocation of callbackFn . Therefore:

  • callbackFn will not visit any elements added beyond the array’s initial length when the call to forEach() began.
  • Changes to already-visited indexes do not cause callbackFn to be invoked on them again.
  • If an existing, yet-unvisited element of the array is changed by callbackFn , its value passed to the callbackFn will be the value at the time that element gets visited. Deleted elements are not visited.

Warning: Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).

The forEach() method is generic. It only expects the this value to have a length property and integer-keyed properties.

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Early termination may be accomplished with looping statements like for , for. of , and for. in . Array methods like every() , some() , find() , and findIndex() also stops iteration immediately when further iteration is not necessary.

forEach() expects a synchronous function — it does not wait for promises. Make sure you are aware of the implications while using promises (or async functions) as forEach callbacks.

const ratings = [5, 4, 5]; let sum = 0; const sumFunction = async (a, b) => a + b; ratings.forEach(async (rating) =>  sum = await sumFunction(sum, rating); >); console.log(sum); // Naively expected output: 14 // Actual output: 0 

To run a series of asynchronous operations sequentially or concurrently, see promise composition.

Examples

Using forEach() on sparse arrays

const arraySparse = [1, 3, /* empty */, 7]; let numCallbackRuns = 0; arraySparse.forEach((element) =>  console.log( element >); numCallbackRuns++; >); console.log( numCallbackRuns >); // // // // 

The callback function is not invoked for the missing value at index 2.

Converting a for loop to forEach

const items = ["item1", "item2", "item3"]; const copyItems = []; // before for (let i = 0; i  items.length; i++)  copyItems.push(items[i]); > // after items.forEach((item) =>  copyItems.push(item); >); 

Printing the contents of an array

Note: In order to display the content of an array in the console, you can use console.table() , which prints a formatted version of the array.

The following example illustrates an alternative approach, using forEach() .

The following code logs a line for each element in an array:

const logArrayElements = (element, index /*, array */) =>  console.log(`a[$index>] = $element>`); >; // Notice that index 2 is skipped, since there is no item at // that position in the array. [2, 5, , 9].forEach(logArrayElements); // Logs: // a[0] = 2 // a[1] = 5 // a[3] = 9 

Using thisArg

The following (contrived) example updates an object’s properties from each entry in the array:

class Counter  constructor()  this.sum = 0; this.count = 0; > add(array)  // Only function expressions will have its own this binding array.forEach(function countEntry(entry)  this.sum += entry; ++this.count; >, this); > > const obj = new Counter(); obj.add([2, 5, 9]); console.log(obj.count); // 3 console.log(obj.sum); // 16 

Since the thisArg parameter ( this ) is provided to forEach() , it is passed to callback each time it’s invoked. The callback uses it as its this value.

Note: If passing the callback function used an arrow function expression, the thisArg parameter could be omitted, since all arrow functions lexically bind the this value.

An object copy function

The following code creates a copy of a given object.

There are different ways to create a copy of an object. The following is just one way and is presented to explain how Array.prototype.forEach() works by using Object.* utility functions.

const copy = (obj) =>  const copy = Object.create(Object.getPrototypeOf(obj)); const propNames = Object.getOwnPropertyNames(obj); propNames.forEach((name) =>  const desc = Object.getOwnPropertyDescriptor(obj, name); Object.defineProperty(copy, name, desc); >); return copy; >; const obj1 =  a: 1, b: 2 >; const obj2 = copy(obj1); // obj2 looks like obj1 now 

Modifying the array during iteration

The following example logs one , two , four .

When the entry containing the value two is reached, the first entry of the whole array is shifted off—resulting in all remaining entries moving up one position. Because element four is now at an earlier position in the array, three will be skipped.

forEach() does not make a copy of the array before iterating.

const words = ["one", "two", "three", "four"]; words.forEach((word) =>  console.log(word); if (word === "two")  words.shift(); //'one' will delete from array > >); // one // two // four console.log(words); // ['two', 'three', 'four'] 

Flatten an array

The following example is only here for learning purpose. If you want to flatten an array using built-in methods, you can use Array.prototype.flat() .

const flatten = (arr) =>  const result = []; arr.forEach((item) =>  if (Array.isArray(item))  result.push(. flatten(item)); > else  result.push(item); > >); return result; >; // Usage const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]]; console.log(flatten(nested)); // [1, 2, 3, 4, 5, 6, 7, 8, 9] 

Calling forEach() on non-array objects

The forEach() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length .

const arrayLike =  length: 3, 0: 2, 1: 3, 2: 4, 3: 5, // ignored by forEach() since length is 3 >; Array.prototype.forEach.call(arrayLike, (x) => console.log(x)); // 2 // 3 // 4 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

  • Polyfill of Array.prototype.forEach in core-js
  • Indexed collections
  • Array
  • Array.prototype.find()
  • Array.prototype.map()
  • Array.prototype.filter()
  • Array.prototype.every()
  • Array.prototype.some()
  • TypedArray.prototype.forEach()
  • Map.prototype.forEach()
  • Set.prototype.forEach()

Found a content problem with this page?

This page was last modified on Jul 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Многомерные массивы в JS

Многомерный массив — это массив, в котором содержится другой массив или другие массивы.

// пример многомерного массива const data = [[1, 2, 3], [1, 3, 4], [4, 5, 6]];

Создание многомерного массива

Пример 1

let studentsData = [['Андрей', 24], ['Настя', 23], ['Даня', 24]];

Пример 2

// одномерные массивы let student1 = ['Андрей', 24]; let student2 = ['Настя', 23]; let student3 = ['Даня', 24]; // многомерный массив let studentsData = [student1, student2, student3];

Оба примера создают одинаковые мнгомерные массивы.

Доступ к элементам многомерного массива

Получить элемент многомерного массива можно обратившись к нему по индексу или индексам.

let x = [ ['Андрей', 24], ['Настя', 23], ['Даня', 24] ]; // получаем первый элемент — это массив console.log(x[0]); // Вывод: ["Андрей", 24] // получаем первый элемент первого «внутреннего» массива console.log(x[0][0]); // Вывод: Андрей // получаем второй элемент третьего «внутреннего» массива console.log(x[2][1]); // Вывод: 24

Многомерный массив x из нашего примера можно представить как таблицу с 3 строками и 2 столбцами.

Добавление элементов в многомерный массив

Добавить элемент в многомерный массив можно с помощью метода push() или с помощью квадратных скобок [] и доступа по индексу. Еще вариант — использовать метод splice() , но он используется реже.

С помощью push()

Давайте добавим элемент во «внешний» массив с помощью метода push() .

let studentsData = [['Андрей', 24], ['Настя', 23],]; studentsData.push(['Даня', 24]); console.log(studentsData); // Вывод: [["Андрей", 24], ["Настя", 23], ["Даня", 24]

Теперь добавим элемент во «внутренний» массив.

let studentsData = [['Андрей, 24], ['Настя', 23],]; studentsData[1].push('привет'); console.log(studentsData); // Вывод: [['Андрей, 24], ['Настя', 23, "привет"]]

С помощью квадратных скобок

// using index notation let studentsData = [['Андрей', 24], ['Настя', 23],]; studentsData[1][2] = 'привет'; console.log(studentsData); // Вывод: [["Андрей", 24], ["Настя", 23, "привет"]]

С помощью splice()

let studentsData = [['Андрей', 24], ['Настя', 23],]; // добавляем элемент на позицию с индексом 1 studentsData.splice(1, 0, ['Даня', 24]); console.log(studentsData); // Вывод: [["Андрей", 24], ["Даня", 24], ["Настя", 23]]

Удаление элементов из многомерного массива

Удалить элемент в многомерный массив можно с помощью метода pop() или с помощью метода splice() .

С помощью pop()

Давайте удалим элемент из «внешнего» массива с помощью метода pop() .

let studentsData = [['Андрей', 24], ['Настя', 23],]; studentsData.pop(); console.log(studentsData); // Вывод: [["Андрей", 24]]

Теперь удалим элемент из внутреннего массива с помощью pop() .

let studentsData = [['Андрей', 24], ['Настя', 23]]; studentsData[1].pop(); console.log(studentsData); // Вывод: [["Андрей", 24], ["Настя"]]

Примечание. Минус метода pop() — он умеет удалять только последний элемент.

С помощью splice()

А вот метод splice() позволяет удалять элемент по определенному индексу.

let studentsData = [['Андрей', 24], ['Настя', 23],]; // удаляем элемент «внешнего» массива с индексом 1 — «внутренний» массив studentsData.splice(1,1); console.log(studentsData); // Вывод: [["Андрей", 24]]

Перебор элементов многомерного массива

С помощью forEach()

Перебрать элементы многомерного массива можно с помощью метода forEach() .

let studentsData = [['Андрей', 24], ['Настя', 23],]; // перебираем элементы массива studentsData studentsData.forEach((student) => < student.forEach((data) =>< console.log(data); >); >);

Первый метод forEach() используется для перебора элементов «внешнего» массива, а второй forEach() — для перебора элементов «внутреннего» массива.

С помощью for. of

Еще вариант для перебора — использовать цикл for. of для прохода по многомерному массиву.

let studentsData = [['Андрей', 24], ['Настя', 23],]; for (let i of studentsData) < for (let j of i) < console.log(j); >>

С помощью цикла for

Перебрать элемента многомерного массива можно и классическим способом — с помощью цикла for .

let studentsData = [['Андрей', 24], ['Настя', 23],]; // проходим по элементам «внешнего» массива for(let i = 0; i < studentsData.length; i++)< // вычисляем длину «внутреннег» массива let innerArrayLength = studentsData[i].length; // проходим по элементам «внутреннего» массива for(let j = 0; j < innerArrayLength; j++) < console.log(studentsData[i][j]); >>

СodeСhick.io — простой и эффективный способ изучения программирования.

2023 © ООО «Алгоритмы и практика»

Источник

Оцените статью