Browse JavaScript fix elements as in C ++ 11

1

In javascript you can traverse an array like it does in other languages like C ++ 11, for example like this:

for(auto i : array) {
   // imprimir i
}

With javascript I have been able to do this:

for(var i in array) {
   // imprimir array[i]
}

The issue is that i does not contain the current items of the array but the index, what I'm asking is if it were possible for i to point to an array value on each pass like C ++ 11 does.

    
asked by nullptr 12.12.2017 в 21:44
source

3 answers

0

Just use for...of

for (var i of [1,2,3,4]) {
    console.log(i)
}
    
answered by 13.12.2017 / 03:32
source
4

There are many ways to traverse an array through JavaScript, here I leave you a few methods:

Using for in cycle

var array = [10,20,30,40,50];

for(var i in array) {
   console.log(array[i])
}

Using map method

var array = [10,20,30,40,50];

array.map(function(dato){
  console.log(dato);
});

Using forEach method

var array = [10,20,30,40,50];

array.forEach(function(dato){
  console.log(dato);
});
    
answered by 12.12.2017 в 21:52
0

The most common is to do it by means of a loop for , although it can be done from other wombs. I leave you two ways to make a for loop, the last of which is commented on in the script.

var array = ["Hola","que","tal","estas"];

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

/*
for (var i in array){
  console.log(array[i]);
}*/
    
answered by 12.12.2017 в 22:22