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?

3
  • 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 Commented May 6, 2012 at 13:37
  • 1
    stackoverflow.com/questions/1267283/… Commented May 6, 2012 at 13:37
  • I know that var positions = [00..totalplayers]; dont work Commented May 6, 2012 at 13:38

4 Answers 4

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Or more simply : arr.push ((i < 10 ? '0' : '') + i)
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)

Comments

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;
}

2 Comments

?? What do you mean with will not suffice and scale when the number is changed?
well if the number was 20000 then would you write i<10000 and i<1000 etc. I was talking before you updated your answer
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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.