2

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

5 Answers 5

8

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]
Sign up to request clarification or add additional context in comments.

2 Comments

I literally need to create a variable like the var n in the question
@tfbox The function option doesn't work for you? Added possibly after your comment
3

I 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.)

Comments

2

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

Comments

1

Another JavaScript method

var number = 12, i = 0, n = [];
while( n.push( i++ ), i <= number );

Comments

0

If you need an array just for iterate through you can doing this : Array(12).fill('');

You just need finding the index from a loop fn to retrieve the current number.

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.