How to make a "for" that saves its values in an array?

Asked

Viewed 122 times

1

I got this one that’s gonna take all the data "this.retorno += data.usuarios[i].descr;" and "this.retorno += data.usuarios[i].valor;" wanted to take this values and make an array with them, then get these values stored in the array on another page with javascript.

I thought of something like this:

var myarry = new Array();

for (i = 0; i < this.qtd; i++) {
  if (i == (this.qtd - 1)) {
    this.retorno += data.usuarios[i].descr;
    this.retorno += data.usuarios[i].valor;
  } else {
    //  this.retorno += data.usuarios[i].descr;
    //  this.retorno += data.usuarios[i].valor;

    myarray[0] = this.retorno += data.usuarios[i].descr;
    myarray[1] = this.retorno += data.usuarios[i].descr;
    myarray[2] = this.retorno += data.usuarios[i].descr;
    myarray[3] = this.retorno += data.usuarios[i].descr;
    myarray[4] = this.retorno += data.usuarios[i].descr;

    alert(myarray[0]);
  }
  • 1

    Utilize: myarray.push(seuvalor); (Also note that your statement is different from the one you use). var myarry = new Array();and you’re calling for myarray.

  • 1

    Do you want each pair to be a position in the array? It would be nice to post a more complete example that can be executed. See How to create a minimal, complete and verifiable example.

  • @bfavaretto That’s even if each pair is an array position !

  • btw, you can use var myarray = [] instead of new Array(). It’s simpler and more efficient.

1 answer

1

As I understand your problem you need to use the .map() so you can use an initial array and redo its contents.

I also see in your code that you want to give a different treatment to the last element, you can use the .pop() which returns the last element of an array and remove it at the same time.

Suggestion:

var ultimo = data.usuarios.pop();
this.retorno += ultimo.descr + ultimo.valor;
var myArray = data.usuarios.map(function(obj){
    return this.retorno += data.usuarios[i].descr;
});

If you don’t understand the answer or need an example, add more code and sample data to the question so I can help you more.

  • has to make each pair a position of the Array ?

  • @nardo_warlock yes, you can make an object for each position. Something like return {descr: ..., val: ... }; but then you’ll end up +/- what you already had initially.

Browser other questions tagged

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