Home > OS >  Everytime variable updates store value inside an array
Everytime variable updates store value inside an array

Time:05-28

Good afternoon wonderful people, So I'm having trouble adding a variable to an array, everytime I push the variable to an array it keeps changing,

i = 5;

function setValue() {
  let a = [];
  a.push(i);
  console.log(a);
}

setValue();

It has to be the same variable, in the app I'm working on is a variable that keeps track of your savings in shopping cart.

CodePudding user response:

In javascript you have to understand the context and the scope.

In your case....You are creating a function....so you are creating a new local context and local scope and in this local context you are defining an array.

When the function is execute..---> setValue(). When the execution ends this local context is removed. And all declared variables are removed too.

So you execute again setValue()...you are creating other context....with new variables( local scope)...so the array a is created again...and you are not doing nothing with this function.

I think your error is don`t know about CONTEXT AND SCOPE in javascript.

https://hackernoon.com/learn-javascript-fundamentals-local-scope-ebxo33fj

CodePudding user response:

For example let's say all the values you want to store inside your a variable are inside this array

const array = [1,2,7,24,8];
let a = [];//initialize a here

Iterate thru that array of values, this iteration might change depending on how you get your data, since I don't know Im just using array as an example

for (let i = 0; i < array.length; i  ) {
    setValue(array[i]);//run your function on each iteration
}

Your function changed to this:

function setValue(val) {
  a.push(val);
}

your output:

console.log(a);//output: [1, 2, 7, 24, 8]

Edit: If the numbers you want to add come from an input then you can do it like this(this approach uses jquery):

<input type="number" id="my_input">

your js:

let a = [];//Declare a outside onchange function
 
//Onchange function to catch the new value everytime input number changes
$("#my_input").on("change", function() {
   var input = $(this).val();//new value from input
   setValue(parseFloat(input));//parseFloat convert string to number and setValue to run your function
   console.log(a);// output
});

Your function:

function setValue(val) {
  a.push(val);//adds new value to array a
}

demo: https://jsfiddle.net/kenpy/5dmsLry0/60/

  • Related