0

I want to store the arguments of abc(10) andabc(15) which is 10 and 15 respectively inside an array var store = [].

var store = [];
function abc(a){
    for (var i = 0; i < 2; i++) {
        store[i] = a;
    }
    console.log(store)
}
abc(10)
abc(15)

Above code's console.log(store) gives me this array [10, 10] and [15, 15]. I want one single array [10, 15] and so on if I call abc(20) 20 array must be added to array and outputs [10, 15, 20].

Abhinash Majhi
  • 499
  • 1
  • 4
  • 16

2 Answers2

1

You could add the parameter to the array with Array#push. Your approach changes the values for each call.

function abc(a) {
    store.push(a);
    console.log(store);
}

var store = [];

abc(10);
abc(15);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Thanks for your answer, but where i wanted to implement it did go like that can you tell me an object way to capture the number. I just wanted to capture the arguments. ```var store = {}``` – Abhinash Majhi May 06 '21 at 13:39
  • 1
    what is the wanted result with an empty object? – Nina Scholz May 06 '21 at 13:40
  • Actually , my goal is to save the argument value somewhere. Array one didn't help me. May be storing in object would work dear. Thanks for helping btw. – Abhinash Majhi May 06 '21 at 13:49
  • the array gives a sorted result of the parameter or anything else. an object needs a key. what keys do you want? – Nina Scholz May 06 '21 at 14:07
0

Firstly you don't need a loop to add values in store. Seconfly you just need to push the values you get in the parameter of abc in store by using store.push(a).

var store = [];
function abc(a){
   store.push(a);
}
abc(10)
abc(15)
M.Hassan Nasir
  • 851
  • 2
  • 13
  • Thanks for your answer, but where i wanted to implement it did go like that can you tell me an object way to capture the number. I just wanted to capture the arguments. ```var store = {}``` – Abhinash Majhi May 06 '21 at 13:40
  • if you want to store the values in an object inside an array this will do that. var store = []; function abc(a){ store.push({key:a}); } – M.Hassan Nasir May 07 '21 at 04:40