Help with array and map

Asked

Viewed 48 times

-1

I have this code, I would like to pull all selected elements and play in an array using map, what am I missing? because it does not return anything;

$('#gerar').on('click',()=>{
    var selecionados = document.querySelectorAll('.select')
    var res = []
    selecionados.map(function(el){
        res.push(el)
    })
    console.log(res)
})
  • Can I put html code? Try using normal function instead of arrow function.

  • 1

    map is to map, not to traverse a array, though as side effect ends up going through it. Why don’t you just res = [...selecionados], by cloning the "array" original?

  • Raul, if you take a list and go through it with a map to add everything to another list, you will only have two identical lists.

  • Thank you all for your help!

1 answer

-2


Using assignment via dismantling, a new ES6 mechanism, try the following:

$('#gerar').on('click', () => {
  //O segredo está aqui: (...)
  var selecionados = [...document.querySelectorAll('.select')];

  var res = []

  selecionados.map(function(el) {
    res.push(el)
  })

  console.log(res)

  //Podes usar o seguinte também:
  //Conforme:
  //https://developer.mozilla.org/en-US/docs/Web/API/NodeList
  var list = document.querySelectorAll('.select');

  let myArry = [];

  Array.prototype.forEach.call(list, function(item) {
    myArry.push(item);
  });

  console.log(myArry);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="select">Texto 1 </div>
<div class="select">Texto 2 </div>
<div class="select">Texto 3 </div>
<div class="select">Texto 4 </div>

<button id="gerar">Teste </button>

  • 1

    I left my -1 because I consider it an incorrect use of map and therefore, in my view, is gambiarra. If the intention is to play all the elements of a array for another, this is not mapping; simply clone the array original.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.