Reputation: 490
I need to limit the number of elements within the array using separate function with arguments N and x where N is the number of elements within the array x.
First, user enters N; second, exactly N elements into an array x
Upvotes: 0
Views: 65
Reputation: 386550
You could take the length for a new array and map all inputs.
function execute(length) {
return Array.from({ length }, (_, i) => prompt('Enter value at index ' + i + ':'));
}
console.log(execute(3));
Upvotes: 1
Reputation: 6491
below will give you the part you need, if the array is not long enough, it will be populated with undefined:
function giveMeNofX(N,x) {
return (x instanceof Array ? x : []).slice(0,N).concat(Array.apply(null,Array(N))).slice(0,N)
}
giveMeNofX(2,[1,2,3]) //1,2
giveMeNofX(100,[1,2,3]) //1,2,3,undefined.....
Based on what you want, freeze
or seal
the returned array.
Upvotes: 0