I want to know if it is possible to make a method that takes two integer values as parameters and returns them and all the numbers between then in an array.
So for example if my method is
function getNumberRange(first, last)
And i call it
getNumberRanger(10, 13)
Is there a way for me to have the answer returned as the following array value
[10, 11, 12, 13]
Thanks in advance and sorry if this is badly worded.
Of course it is.
function getNumberRange(first, last) {
var arr = [];
for (var i = first; i <= last; i++) {
arr.push(i);
}
return arr;
}
You may even want to add a check to make sure first is indeed last than greatest though to avoid errors. Maybe something like this:
if (first > last) {
throw new Error("first must be less than last");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With