Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A method that takes 2 integer values and returns an array. JavaScript [duplicate]

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.

like image 570
RobStallion Avatar asked Apr 11 '26 18:04

RobStallion


1 Answers

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");
}
like image 167
thatidiotguy Avatar answered Apr 17 '26 01:04

thatidiotguy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!