prime90
prime90

Reputation: 959

Appending an array with a for loop

I'm trying to write a function to append an array with a for loop. The data I'm trying to append is in a JSON repsonse. However, I keep getting x10 Array[] in the web console instead of one array with all the data. When I run console.log(dates[0]) I get returned in the web console "undefined". This tells me the data isn't even making it into the array. When I run console.log(time) I return x10 peices of data from the JSON I want but of course its not in the array. Any ideas? Thanks.

function mostRecent(time) {
    var dates=[];
    for (var i = 0; i < time.length; i++) {
        dates.push(dates[i]);
    }
    return console.log(dates);
    }

Upvotes: 0

Views: 70

Answers (1)

kind user
kind user

Reputation: 41893

You are pushing dates[i] with every loop cycle. And since dates array keeps being empty, you are actually pushing undefined.

Just replace dates.push(dates[i]) with dates.push(time[i]).

Note: You should return dates instead of console.log.

Upvotes: 3

Related Questions