Iterations within a map

2

I want to iterate over each word, with a for or map but I do not know how to do it

I want to iterate the characters of the strings in the for that is inside the map

array=["hola","mundo"];
     array.map(value=>
            for(let i=0; i<value.length; i++){

        }
            )
    
asked by hubman 13.03.2018 в 22:05
source

4 answers

2

Actually, the map function already iterates through your elements. You do not need to add any additional iterations with any loop.

This function will go through each of the elements of your array and will return a new array with the result. As in your case, you do not need to return, you only need to show the results with a console.log , you can show it directly within the function.

To traverse the characters of each word you can use the split function to divide the text strings into an array with their characters and then a foreach loop to scroll through and display them.

Your modified example:

var array=["hola","mundo"];

var arrayObtenido = array.map(function(elemento){ 
   console.log("Texto: " + elemento);
   var caracteres = elemento.split("");
   caracteres.forEach(function(caracter) {
      console.log(caracter);
   }); 
});
    
answered by 13.03.2018 / 22:13
source
2

Greetings with the map method, you can do the tour as follows:

palabras = ["hola", "mundo"]

var dictado = palabras.map((palabra) => {
  console.log(palabra)
})

As you can see I declare the variable dictated to contain the loop that will be made, inside the map method with an arrow function I pass as an argument to word because it will be the variable that now has each attribute of the array recognized that I declared above.

One more way of doing iterations without a for or foreach for example at least not explicitly

Greetings

    
answered by 13.03.2018 в 22:16
1

With a for it could be like that

    let miArray = ["hola","mundo"];
    
    for ( let i = 0; i < miArray.length; i++ ) {
        console.log(miArray[i]);
    }
    
answered by 13.03.2018 в 22:13
1

I could use the forEach in this way:

let array=["hola","mundo"];
array.forEach(element=>{
    console.log(element);
});
    
answered by 13.03.2018 в 22:12