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 mand I can call that creates such an array?
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 mand I can call that creates such an array?
Share Improve this question edited Feb 15, 2017 at 22:56 John Wu 52.3k8 gold badges47 silver badges90 bronze badges asked Feb 15, 2017 at 22:53 Ulysse CorbeilUlysse Corbeil 791 gold badge3 silver badges11 bronze badges 5- In what language? Can it be lazy? Obviously there is finite storage available. – Dave Newton Commented Feb 15, 2017 at 22:54
- In javascript, I am new to programming and not that familiar with these concepts. – Ulysse Corbeil Commented Feb 15, 2017 at 22:55
- Perhaps you mean arbitrary-length arguments list instead of infinite-length array? – Chris Trahey Commented Feb 15, 2017 at 22:56
- Well, my goal is to create a function that would return any length of numbers and put them in a table, how would I go about this? – Ulysse Corbeil Commented Feb 15, 2017 at 22:59
- This isn't an "infinite array," but a variadic function. Infinite arrays don't exist in JavaScript, but you can overloading the [] operator to make an object with an "infinite" number of elements. – Anderson Green Commented Dec 1, 2023 at 5:18
4 Answers
Reset to default 3In 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.
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);
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./js/js_function_parameters.asp
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 acplish this.
add(...numbers) {
// numbers is the array of arguments
// implement the addition of values in the array
}
add(1, 2, 3, 5, 8)