BelugaSanity
BelugaSanity

Reputation: 33

pass a number into an array using a for loop

I have to do a function to return an array with all positive numbers from 0 to n (inclusive, meaning n should be included in the array and n will be a number passed to the function as parameter.

This is what i have:

function arrayWithNumbersUpTo(n) {
    for(var i = 0; i <= n; i++) {
        arr.push(i);
        return arr;
    }
}
var arr = [];

I've been struggling for over two hours to do what I am sure is a simple solution, please help!

Upvotes: 0

Views: 171

Answers (1)

A.J. Uppal
A.J. Uppal

Reputation: 19264

You have to call the return outside the for loop:

function arrayWithNumbersUpTo(n){
    var arr = [];
    for(var i = 0; i <= n; i++){
        arr.push(i);
    }
    return arr;
}

Upvotes: 1

Related Questions