9

Possible Duplicate:
Does JavaScript have a range() equivalent?

Is there a way to declare a range in Javascript/jQuery like we do in Python?

Something like this:

x = range(1,10)

x = [1,2,3,4,5,6,7,8,9]

Thanks.

1
  • 1
    For fun try: function r(start,end){ start = start || 1; return end >= start ? r(start,end-1).concat(end) : []; } Commented Aug 4, 2012 at 14:00

3 Answers 3

5

By using some third party libraries like Underscore.js you can achieve the same behaviour as in Python http://underscorejs.org/#range

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

Comments

3

You simply can create an array, loop over the values using a for loop and pushing the values. There isn't anything built into the language.

Comments

3

Put this function in your Javascript code, and you should be able to call range() like you do in Python (but it only works for numbers):

function range(start, end)
{
    var array = new Array();
    for(var i = start; i < end; i++)
    {
        array.push(i);
    }
    return array;
}

3 Comments

Just interesting, how may [1..10] be implemented? =)
You mean for (var i = start; i < end; i++)
Definitely useful, but not exactly like range in Python.. docs.python.org/library/functions.html#range :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.