Reputation: 1880
Let's say that i got a variable which it contains the number 19. I want to make an array from it with the following numbers
var positions = [ "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19" ];
How is this possible in javascript?
Upvotes: 0
Views: 2806
Reputation: 122936
Alternatively:
var mynumber = 19,
myarr = String(Array(mynumber+1))
.split(',')
.map(function(el,i){return i<10 ? '0'+i : ''+i;});
For zeropadding you may want to use:
function padLeft(nr,base,chr){
base = base || 10;
chr = chr || '0';
var len = (String(base).length - String(nr).length)+1;
return len > 0? Array(len).join(chr)+nr : nr;
}
// usage
padLeft(1); //=> '01'
padLeft(1,100); //=> '001'
padLeft(1,10000,'-'); //=> '----1'
Update 2019: in es20xx String.prototype
contains a native padStart
method:
"1".padStart(2, "0"); //=> "01"
// ^ max length
// ^ fill string (or space if omitted)
Upvotes: 2
Reputation: 113
Using this example finally solved my own @@iterator function interface issue; Thanks a lot
var myArray = [];
function getInterval (start, step, end, ommit){
for (start; start <= end; start += step) {
myArray.push( start < 10 ? ("" + start.toString()) : start.toString());
}
}
getInterval(2, 2, 20, 20);
myArray; // __proto__: Array
// (10) ["2", "4", "6", "8", "10", "12", "14", "16", "18", "20"]
myArray[4]; // "10"
Upvotes: 1
Reputation: 15579
essentially you want to pad 0's and the answers here will not suffice and scale when the number is changed.. Probably the better solution would be
function padZero(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
Upvotes: 1
Reputation: 19581
Something like :
var number = 19;
var arr = [];
for ( i = 0; i <= number ; i++ ) {
arr.push(i < 10 ? ("0" + i.toString()) : i.toString());
}
demo : http://jsfiddle.net/Kfnnr/1/
Upvotes: 3