Or in another way how to iterate through all the elements of an array in Javascript?

Something like foreach(array as value)

6 answers 6

There are several options, depending on your tasks.

Let's start with the simple:

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

A slightly more old-fashioned option:

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

In addition, there is actually for-in . It can be used, for example, for sparsed arrays:

Primitive, but not quite the right option:

 for (var key in data) { key;//ключ data[key];//значение } 

More correct:

 var key; var a = []; a[0] = "a"; a[10] = "b"; a[10000] = "c"; for (key in a) { if (a.hasOwnProperty(key) && /^0$|^[1-9]\d*$/.test(key) && key <= 4294967294 ) { console.log(a[key]); } } 

In EcmaScript6, a for-of construction has been added as a proposal (draft):

 var val; var a = ["a", "b", "c"]; for (val of a) { console.log(val); } 

Actually, by and large, for-of is just the right for-in , not requiring additional checks as in the example above. The principal differences in the details can be found in the proposal (English).

More details:

  • Another for-of worth adding. - uhbif19
  • one
    @ uhbif19: I fully agree and support. Added. - Igor Chubin 5:09

In standard JavaScript, arrays have a forEach method:

 ['a', 'b', 'c'].forEach(function(value, index) { console.log('a[' + index + '] = ' + value); }); 

We get:

 a[0] = a a[1] = b a[2] = c 

Not to be confused with the for (key in object) construct. Such a construction enumerates the properties of an object , rather than the elements of an array. Although array elements are considered to be its properties, you will not only get them, and you will have to filter the properties with hasOwnProperty .

     for (var i = 0; i < array.length; i++) { console.log(array[i]); } 

      You can use the $.each function https://api.jquery.com/each/

         for (var i = 0; i <= myArray.length; i++) { /*тут делаем что нужно с myArray[i]*/ } 

          see the implementation of Array.prototype.forEach ()

          Syntax

           arr.forEach(callback[, thisArg]) 

          Options

          callback The function that creates the element of the new array takes three arguments:

          • currentValue The current item being processed in the array.

          • index The index of the current item being processed in the array.

          • array The array to pass through.

          thisArg Optional parameter. The value used as this when calling the callback function.

          The following code prints each element of the array on a new log line:

           function logArrayElements(element, index, array) { console.log('a[' + index + '] = ' + element); } // Обратите внимание на пропуск по индексу 2, там нет элемента, поэтому он не посещается [2, 5, , 9].forEach(logArrayElements); // логи: // a[0] = 2 // a[1] = 5 // a[3] = 9 

            Protected by spirit community member 7 Apr '15 at 12:42 .

            Thank you for your interest in this issue. Since he collected a large number of low-quality and spam responses, which had to be deleted, now it’s necessary to have 10 reputation points on the site (the bonus for account association is not counted ).

            Maybe you want to answer one of the unanswered questions ?