I want to design some arrays like [1..25] in JavaScript, but I don't want to do by hand ([1, 2, 3, 4, 5, 6, [...], 25]).
How would you do?
Well you could make a simple function...
function range(min, max) {
var len = max - min + 1;
var arr = new Array(len);
for (var i=0; i<len; i++) {
arr[i] = min + i;
}
return arr;
}
range(1,10);
// [1,2,3,4,5,6,7,8,9,10]
This answer is not the smallest amount of code, but it's very readable and tremendously faster than any other solution provided here.
new Array(len) can be just [].new Array(len) is better.[] when I'm working with an array of unknown size, but why would you give up tons of speed just to write [] instead of new Array(len)?If the your elements are related (the incrementation is fixed fro instance), you can do this with a loop:
for(var i = 1; i<=25; i++) {myArray.push(i);}
You could add the numbers in a loop eg:
var array = [];
for (var i=1; i<26; i++) {
array[i-1] = i;
}
var i=1; i<=25 imovar min = 1, max = 25;
Array.apply(null, Array(max - min + 1)).map(function (i,j) {
return j + min;
});
Look ma, no for or while! Set it into Array for convenience: (Using Array as namespace)
Array.range = function(min, max){
return this.apply(null, this(max - min + 1)).map(function (i,j) {
return j + min;
});
};
Array.range(1, 25); //[1..25]
forloop should be simple enough.range()function in another language to be equivalent in JS. If I know how to search for a simple thing like this, I probably didn't create a topic. And another thing: what's wrong with my question? The negatives are because it is "duplicate"?