0

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?

Alex Bogias
  • 1,826
  • 2
  • 30
  • 45
  • i know that i if the number is for example 9 i can make it 09 with the following line: `var totalplayers = ("0" + totalplayers).slice(-2);` But i cant build an array with all the numbers from 00 to totalplayers – Alex Bogias May 06 '12 at 13:37
  • 1
    http://stackoverflow.com/questions/1267283/how-can-i-create-a-zerofilled-value-using-javascript – jbabey May 06 '12 at 13:37
  • I know that var positions = [00..totalplayers]; dont work – Alex Bogias May 06 '12 at 13:38

4 Answers4

3

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/

drinchev
  • 19,201
  • 4
  • 67
  • 93
2

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)
KooiInc
  • 119,216
  • 31
  • 141
  • 177
1

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;
}
Baz1nga
  • 15,485
  • 3
  • 35
  • 61
  • ?? What do you mean with *will not suffice and scale when the number is changed*? – KooiInc May 06 '12 at 14:07
  • well if the number was 20000 then would you write i<10000 and i<1000 etc. I was talking before you updated your answer – Baz1nga May 06 '12 at 14:16
1

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"
projektorius96
  • 114
  • 2
  • 10