Say for instance I have the number 12:
var number = 12;
How could I change that number into something like:
var n = [0,1,2,3,4,5,6,7,8,9,10,11,12];
Someone probably has a jQuery shortcut, but here's a plain JavaScript solution:
var num = 12;
var n = [];
for (var i=0; i <= num; i++) {
n.push(i);
}
As a function:
function num2Array(num) {
var n = [];
for (var i=0; i <= num; i++) {
n.push(i);
}
return n;
}
console.log(num2Array(15));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
var n in the questionI actually had this function sitting around:
function number_range(beginning, end) {
var numbers = [];
for (; beginning <= end; beginning++) {
numbers[numbers.length] = beginning;
}
return numbers;
}
So if you need to generate more than one of these arrays, it could be useful:
var n = number_range(0, 12);
As for jQuery, well... I don't think that's necessary in this case. (I also don't know of any such function off the top of my head.)
jQuery doesn't have this, but you could use underscore.js:
http://documentcloud.github.com/underscore/#range
_.range([start], stop, [step])
So you could do:
var n = _.range(12);
Or:
var n = _.range(0, 12);