Foreach js для массивов и коллекций. JQuery - Перебор массива, объекта и элементов. II. Перебор массивоподобных объектов

Последнее обновление: 26.03.2018

Объект Array представляет массив и предоставляет ряд свойств и методов, с помощью которых мы можем управлять массивом.

Инициализация массива

Можно создать пустой массив, используя квадратные скобки или конструктор Array:

Var users = new Array(); var people = ; console.log(users); // Array console.log(people); // Array

Можно сразу же инициализировать массив некоторым количеством элементов:

Var users = new Array("Tom", "Bill", "Alice"); var people = ["Sam", "John", "Kate"]; console.log(users); // ["Tom", "Bill", "Alice"] console.log(people); // ["Sam", "John", "Kate"]

Можно определить массив и по ходу определять в него новые элементы:

Var users = new Array(); users = "Tom"; users = "Kate"; console.log(users); // "Tom" console.log(users); // undefined

При этом не важно, что по умолчанию массив создается с нулевой длиной. С помощью индексов мы можем подставить на конкретный индекс в массиве тот или иной элемент.

length

Чтобы узнать длину массива, используется свойство length :

Var fruit = new Array(); fruit = "яблоки"; fruit = "груши"; fruit = "сливы"; document.write("В массиве fruit " + fruit.length + " элемента:
"); for(var i=0; i < fruit.length; i++) document.write(fruit[i] + "
");

По факту длиной массива будет индекс последнего элемента с добавлением единицы. Например:

Var users = new Array(); // в массиве 0 элементов users = "Tom"; users = "Kate"; users = "Sam"; for(var i=0; i 0) { result = true; } return result; }; var passed = numbers.every(condition); document.write(passed); // false

В метод every() в качестве параметра передается функция, представляющая условие. Эта функция принимает три параметра:

Function condition(value, index, array) { }

Параметр value представляет текущий перебираемый элемент массива, параметр index представляет индекс этого элемента, а параметр array передает ссылку на массив.

В этой функции мы можем проверить переданное значение элемента на соответствие какому-нибудь условию. Например, в данном примере мы проверяем каждый элемент массива, больше ли он нуля. Если больше, то возвращаем значение true , то есть элемент соответствует условию. Если меньше, то возвращаем false - элемент не соответствует условию.

В итоге, когда происходит вызов метода numbers.every(condition) он перебирает все элементы массива numbers и по очереди передает их в функцию condition . Если эта функция возвращает значение true для всех элементов, то и метод every() возвращает true . Если хотя бы один элемент не соответствует условию, то метод every() возвращает значение false .

some()

Метод some() похож на метод every() , только он проверяет, соответствует ли хотя бы один элемент условию. И в этом случае метод some() возвращает true . Если элементов, соответствующих условию, в массиве нет, то возвращается значение false:

Var numbers = [ 1, -12, 8, -4, 25, 42 ]; function condition(value, index, array) { var result = false; if (value === 8) { result = true; } return result; }; var passed = numbers.some(condition); // true

filter()

Метод filter() , как some() и every() , принимает функцию условия. Но при этом возвращает массив тех элементов, которые соответствуют этому условию:

Var numbers = [ 1, -12, 8, -4, 25, 42 ]; function condition(value, index, array) { var result = false; if (value > 0) { result = true; } return result; }; var filteredNumbers = numbers.filter(condition); for(var i=0; i < filteredNumbers.length; i++) document.write(filteredNumbers[i] + "
");

Вывод в браузере:

1 8 25 42

forEach() и map()

Методы forEach() и map() осуществляют перебор элементов и выполняют с ними определенный операции. Например, для вычисления квадратов чисел в массиве можно использовать следующий код:

Var numbers = [ 1, 2, 3, 4, 5, 6]; for(var i = 0; i

  • HTML
  • JavaScript
$("ul#myList").children().each(function(){ console.log($(this).text()); }); // Результат: // HTML // CSS // JavaScript

Рассмотрим способ, с помощью которого можно определить последний индекс (элемент) в методе jQuery each .

// выбираем элементы var myList = $("ul li"); // определяем количество элементом в выборке var total = myList.length; // осуществляем перебор выбранных элементов myList.each(function(index) { if (index === total - 1) { // это последний элемент в выборке } });

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

The source for this interactive example is stored in a GitHub repository. If you"d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Syntax arr .forEach(callback(currentValue [, index [, array]]) [, thisArg ]) Parameters callback Function to execute on each element. It accepts between one and three arguments: currentValue The current element being processed in the array. index Optional The index currentValue in the array. array Optional The array forEach() was called upon. thisArg Optional Value to use as this when executing callback . Return value Description

forEach() calls a provided callback function once for each element in an array in ascending order. It is not invoked for index properties that have been deleted or are uninitialized. (For sparse arrays, .)

callback is invoked with three arguments:

  • the value of the element
  • the index of the element
  • the Array object being traversed
  • If a thisArg parameter is provided to forEach() , it will be used as callback"s this value. The thisArg value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function .

    The range of elements processed by forEach() is set before the first invocation of callback . Elements which are appended to the array after the call to forEach() begins will not be visited by callback . If existing elements of the array are changed or deleted, their value as passed to callback will be the value at the time forEach() visits them; elements that are deleted before being visited are not visited. If elements that are already visited are removed (e.g. using shift()) during the iteration, later elements will be skipped. (See this example, below .)

    forEach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.

    forEach() does not mutate the array on which it is called. (However, callback may do so)

    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:

    Array methods: every() , some() , find() , and findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.

    Examples No operation for uninitialized values (sparse arrays) const arraySparse = let numCallbackRuns = 0 arraySparse.forEach(function(element){ console.log(element) numCallbackRuns++ }) console.log("numCallbackRuns: ", numCallbackRuns) // 1 // 3 // 7 // numCallbackRuns: 3 // comment: as you can see the missing value between 3 and 7 didn"t invoke callback function. Converting a for loop to forEach const items = ["item1", "item2", "item3"] const copy = // before for (let i = 0; i < items.length; i++) { copy.push(items[i]) } // after items.forEach(function(item){ copy.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:

    Function 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... .forEach(logArrayElements) // logs: // a = 2 // a = 5 // a = 9

    Using thisArg

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

    Function Counter() { this.sum = 0 this.count = 0 } Counter.prototype.add = function(array) { array.forEach(function(entry) { this.sum += entry ++this.count }, this) // ^---- Note } const obj = new Counter() obj.add() obj.count // 3 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.

    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 ECMAScript 5 Object.* meta property functions.

    Function copy(obj) { const copy = Object.create(Object.getPrototypeOf(obj)) const propNames = Object.getOwnPropertyNames(obj) propNames.forEach(function(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

    If the array is modified during iteration, other elements might be skipped.

    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.

    Let words = ["one", "two", "three", "four"] words.forEach(function(word) { console.log(word) if (word === "two") { words.shift() } }) // one // two // 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() (which is expected to be part of ES2019, and is already implemented in some browsers).

    /** * Flattens passed array in one dimensional array * * @params {array} arr * @returns {array} */ function flatten(arr) { const result = arr.forEach((i) => { if (Array.isArray(i)) { result.push(...flatten(i)) } else { result.push(i) } }) return result } // Usage const problem = , 8, 9]] flatten(problem) //

    Note on using Promises or async functions let ratings = 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: 0 Specifications Specification Status Comment
    ECMAScript Latest Draft (ECMA-262)
    Draft
    ECMAScript 2015 (6th Edition, ECMA-262)
    The definition of "Array.prototype.forEach" in that specification.
    Standard
    ECMAScript 5.1 (ECMA-262)
    The definition of "Array.prototype.forEach" in that specification.
    Standard Initial definition. Implemented in JavaScript 1.6.
    Browser compatibility

    The compatibility table in this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

    Update compatibility data on GitHub

    Desktop Mobile Server Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js forEach
    Chrome Full support 1 Edge Full support 12 Firefox Full support 1.5 IE Full support 9 Opera Full support Yes Safari Full support 3 WebView Android Full support ≤37 Chrome Android Full support 18 Firefox Android Full support 4 Opera Android Full support Yes Safari iOS Full support 1 Samsung Internet Android Full support 1.0 nodejs Full support Yes
    • I. Перебор настоящих массивов
    • Метод forEach и родственные методы
    • Цикл for
    • Правильное использование цикла for...in
    • Цикл for...of (неявное использование итератора)
    • Явное использование итератора
    • II. Перебор массивоподобных объектов
    • Использование способов перебора настоящих массивов
    • Преобразование в настоящий массив
    • Замечание по объектам среды исполнения
    I. Перебор настоящих массивов

    На данный момент есть три способа перебора элементов настоящего массива:

  • метод Array.prototype.forEach ;
  • классический цикл for ;
  • «правильно» построенный цикл for...in .
  • Кроме того, в скором времени, с появлением нового стандарта ECMAScript 6 (ES 6), ожидается еще два способа:

  • цикл for...of (неявное использование итератора);
  • явное использование итератора.
  • 1. Метод forEach и родственные методы

    Если ваш проект рассчитан на поддержку возможностей стандарта ECMAScript 5 (ES5), вы можете использовать одно из его нововведений - метод forEach .

    Пример использования:

    Var a = ["a", "b", "c"]; a.forEach(function(entry) { console.log(entry); });

    В общем случае использование forEach требует подключения библиотеки эмуляции es5-shim для браузеров, не имеющих нативной поддержки этого метода. К ним относятся IE 8 и более ранние версии, которые до сих пор кое-где еще используются.

    К достоинствам forEach относится то, что здесь не нужно объявлять локальные переменные для хранения индекса и значения текущего элемента массива, поскольку они автоматически передаются в функцию обратного вызова (колбек) в качестве аргументов.

    Если вас беспокоят возможные затраты на вызов колбека для каждого элемента, не волнуйтесь и прочитайте это .

    forEach предназначен для перебора всех элементов массива, но кроме него ES5 предлагает еще несколько полезных методов для перебора всех или некоторых элементов плюс выполнения при этом каких-либо действий с ними:

    • every - возвращает true , если для каждого элемента массива колбек возвращает значение приводимое к true .
    • some - возвращает true , если хотя бы для одного элемента массива колбек возвращает значение приводимое к true .
    • filter - создает новый массив, включающий те элементы исходного массива, для которых колбек возвращает true .
    • map - создает новый массив, состоящий из значений возращаемых колбеком.
    • reduce - сводит массив к единственному значению, применяя колбек по очереди к каждому элементу массива, начиная с первого (может быть полезен для вычисления суммы элементов массива и других итоговых функций).
    • reduceRight - работает аналогично reduce, но перебирает элементы в обратном порядке.
    2. Цикл for

    Старый добрый for рулит :

    Var a = ["a", "b", "c"]; var index; for (index = 0; index < a.length; ++index) { console.log(a); }

    Если длина массива неизменна в течение всего цикла, а сам цикл принадлежит критическому в плане производительности участку кода (что маловероятно), то можно использовать «более оптимальную» версию for с хранением длины массива:

    Var a = ["a", "b", "c"]; var index, len; for (index = 0, len = a.length; index < len; ++index) { console.log(a); }

    Теоретически этот код должен выполняться чуть быстрее, чем предыдущий.

    Если порядок перебора элементов не важен, то можно пойти еще дальше в плане оптимизации и избавиться от переменной для хранения длины массива, изменив порядок перебора на обратный:

    Var a = ["a", "b", "c"]; var index; for (index = a.length - 1; index >= 0; --index) { console.log(a); }

    Тем не менее, в современных движках JavaScript подобные игры с оптимизацией обычно ничего не значат.

    3. Правильное использование цикла for...in

    Если вам посоветуют использовать цикл for...in , помните, что перебор массивов - не то, для чего он предназначен . Вопреки распространенному заблуждению цикл for...in перебирает не индексы массива, а перечислимые свойства объекта.

    Тем не менее, в некоторых случаях, таких как перебор разреженных массивов , for...in может оказаться полезным, если только соблюдать при этом меры предосторожности, как показано в примере ниже:

    // a - разреженный массив var a = ; a = "a"; a = "b"; a = "c"; for (var key in a) { if (a.hasOwnProperty(key) && /^0$|^d*$/.test(key) && key

    Есть вопросы?

    Сообщить об опечатке

    Текст, который будет отправлен нашим редакторам: