简体   繁体   中英

how to push value to array

I have this function

getVal(item){
  var data = [];
  data.push(item);
  console.log(data);
}

the value of the variable item is:

4.9000
6.7000

I want to insert into an array, but the result in my console is this:

4.9000
6.7000

I want the output to be this: [4.9000, 6.7000 ]

Do I have to merge first? Or maybe my push technique is wrong?

Remove data from getVal scope. here you make a new array for each execution

var data = [];
getVal(item){
  data.push(item);
  console.log(data);
}

Your logic with push function is right. But the problem is every time the function run, you clear all the previous value.

An alternative solution is to declare it outside or you could run a for loop:

 let data = []; function getVal(item){ data.push(item); } getVal(1) getVal(2) console.log(data);

Run a for loop:

 let data = []; function getVal(item){ let data = [] for(let i in item){ data.push(i); } console.log( data) } getVal([1,2,3])

You have to move the initialization of data out of the function body. You can avoid the global variable using a closure and an IIFE

const getVal = (() => {
  const data = [];
  return (item) => {
    data.push(item);
    console.log(data);
  }
})();

Example:

 const getVal = (() => { const data = []; return (item) => { data.push(item); console.log(data); } })(); getVal(1); getVal(2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM