Say I have the following checkbox:
<input type="checkbox" value="1-25" />
To get the two numbers that define the boundaries of range I'm looking for, I use the following jQuery:
var value = $(this).val();
var lowEnd = Number(value.split('-')[0]);
var highEnd = Number(value.split('-')[1]);
How do I then create an array that contains all integers between lowEnd
and highEnd
, including lowEnd
and highEnd
themselves? For this specific example, obviously, the resulting array would be:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
fastest way
function:
or
EDIT
readable version
Demo
http://jsfiddle.net/W3CUn/
FOR THE DOWNVOTERS
performance
http://jsperf.com/for-push-while-set/2
faster in ie and 3x faster in firefox
only on aipad air the for loop is a little faster.
tested on win8, osx10.8, ubuntu14.04, ipad, ipad air, ipod;
with chrome,ff,ie,safari,mobile safari.
i would like to see the performance on older ie browsers where the for loop isn't that optimized!
There's probably a DRYer way to do the loop, but that's the basic idea.
My five cents:
Both direction array of integers function.
When range(0, 5) become
[0, 1, 2, 3, 4, 5]
.And range(5, 0) become
[5, 4, 3, 2, 1, 0]
.Based on this answer.
P.S. For use in real life you should also check args for
isFinite()
andisNaN()
.If the start is always less than the end, we can do:
If we want to be able to take a third argument to be able to modify the step used to build the array, and to make it work even though the start is greater than the end:
This way the function accepts positive and negative steps and if no step is given, it defaults to 1.
ES6 :