3

I was wondering if it would be possible to create an array infinitely long, so that any number I would put in my function : for exemple : function arr(2,3,4,5,6,7), would be treated as an array and put in a "table", but it didn't mather how many number I put in, the table would just extend! Is there a command I can call that creates such an array?

John Wu
  • 50,556
  • 8
  • 44
  • 80
Ulysse Corbeil
  • 81
  • 1
  • 3
  • 9

4 Answers4

3

In JavaScript, inside any function there is a variable available called arguments. You can treat it like an array, and enumerate the arguments passed into the function, no matter how many there are.

Chris Trahey
  • 18,202
  • 1
  • 42
  • 55
  • 1
    Well, technically, arrow functions don't have an `arguments` variable, but I expect the OP isn't worrying about that yet. – Heretic Monkey Feb 15 '17 at 23:07
2

You can add as many as you want, but it's gonna make your browser slow, or just crash it.
But you can reset your array when you are done with it.
An array is technically infinite if you don't limit it when its initialised, but storage is finite, so be careful.

var myarray = [];
function arr(elements) {
  myarray.push(elements);
}
arr(1);
arr(2);
arr(3);
console.log(myarray);
myarray = [];
arr(4);
arr(5);
arr(6);
console.log(myarray);
JKhan
  • 90
  • 1
  • 7
0

javascript treats arguments as an array that can be called within the function as

var myFunction = function(){
  console.log(arguments[i]);
}

if you want to pass an array as a list of arguments to the array use:

var myArray = [1,2,3];
myFunction(...myArray);

more: https://www.w3schools.com/js/js_function_parameters.asp

xxfast
  • 697
  • 5
  • 14
0

It looks to me like you want a function that takes N number of arguments and puts them into an array. You can use this syntax to accomplish this.

add(...numbers) {
  // numbers is the array of arguments
  // implement the addition of values in the array
}

add(1, 2, 3, 5, 8)
golson2295
  • 36
  • 3