What would be the tersest way to create this array:
var x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
For example, a for
loop:
var x = [];
for (var i=1;i<=20;i++) {
x.push(i);
}
Or a while
loop:
var x = [], i = 1, endInt = 20;
while (i <= endInt) {
x.push(i);
i++;
}
Would there be other examples that would be terser -- in other words -- less code? I'm thinking of things like in Ruby where the equivalent code I believe would be as simple as 1..20
. I'm not aware of syntax like that in JavaScript but I'm wondering if there are shorter ways to do that same thing.
UPDATE: I wasn't thinking of removing semicolons or var
for answers in the question, but I have to admit the question implies that. I am more curious about algorithms than shaving bytes. Sorry if I was unclear! Also, making it into a function is simple enough, just slap function range(start, end) { /* guts here */ }
around it and you're there. The question is are there novel approaches to the "guts."
var $x = range(1, 20);
... like, why not in JavaScript? – artlung Jun 9 '11 at 21:28range()
in JS and use that? – svick Jun 9 '11 at 21:30push()
method is actually not very smart here because of dynamic array growth. If you know the number of fields beforehand, you should use a size-explicit initializing and fill the fields via indexing:x[i-start_i] = i;
– Martin Hennings Jun 9 '11 at 21:32