Save information from a vector to each function call

0

I have a function in my javascript code, in this function is filled information into a variable that will be added in 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 the function it will read the vector with all the scanners already collected and thus updating the previous values. That is, if once the vector was ["hi"] and then it became ["hi", "hello"], the final result of all 'Response session' that I pushed to the 'mySessions' vector will be the last value of the vector: [["hi", "hello"], ["hi", "hello"], thus losing the state of the vector when it was only ["hi"]. The desired result for this would be: [["hi"], ["hi", "hi"]]

    
asked by anonymous 15.02.2018 / 23:16

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 local scope vector of your function.

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's the fiddle link for example.

    
16.02.2018 / 12:11