Save information from an array to each function call

Asked

Viewed 42 times

0

have a function in my javascript code, in this function is filled information in a variable that will be added at the position of a vector, I will try to illustrate with parts in pseudocode the example:

funcao(){
   a = scan;
   vetor.push(a);
   //codigo do json:
   var sessaoResposta = {"respostas": vetor};
   mySessions.push(sessaoResposta);
   console.log(JSON.stringify(mySessions));
}

The problem is that the final result in the console will always be the complete array with the same data (which is the final data), all passed from the function it will read the vector with all scanners already collected and thus updating the previous values. That is, if once the vector was ["hi"] and then became ["hi","ola"], the final result of all the 'sessaoResposta' that I pushed pro vector 'mySessions' will be the last value of the vector : [["hi","ola"] ,["hi","ola"]], thus losing the state of the vector when it was only ["hi"]]. The desired result for this would be: [["hi"] ,["hi","hello"]]

1 answer

0

This happens because you are always using the same reference of vetor that is global. You can solve this by creating a vector of local scope of your job.

function funcao(){
   a = scan;
   vetor.push(a);
   let novoVetor = [].concat(vetor);

   //codigo do json:
   var sessaoResposta = {"respostas": novoVetor};
   mySessions.push(sessaoResposta);
   console.log(JSON.stringify(mySessions));
}

Here the link from fiddle to exemplify.

  • vi also that with the function 'Slice()' it is possible to save by copy

  • @Dr.G, almost all array functions in javascript return a new array as a result. The function of splice() wouldn’t be exactly for this case, but if it met your purpose, we can’t say it’s more right or more wrong. I suggest taking a look at this one link, is very useful.

Browser other questions tagged

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