0

I have a really simple home made API that reads the content of some files on the server, parse them and send their content in JSON.

My webpage calls the API using Ajax, reads the data and store them on custom objects. The problem is that, no matter of much files I have parsed in my JSON, only the first one is treated my the Javascript code.

runs = [];

function Solution(values) {
    this.number = values[0]
    this.weight = values[1]
    this.value = values[2]
    this.score = values[3]
}

function DateValue(date) {
    regex = new RegExp(/(\d{4})-(\d{1,2})-(\d{1,2})-(\d{1,2}):(\d{1,2}):(\d{1,2})-(\d{1,2})/)
    dateArray = date.split(regex)
    this.year = dateArray[1]
    this.month = dateArray[2]
    this.day = dateArray[3]
    this.hour = dateArray[4]
    this.minutes = dateArray[5]
    this.secondes = dateArray[6]
}           

function Run(values) {
    this.algorithm = values["log"]["Algorithm used"]
    this.weight = values["log"]["Weight"]
    this.value = values["log"]["Value"]
    this.date = new DateValue(values["log"]["Date"])
    this.solutions = []
    for(i = 0; i < values["datas"].length; i++) {
        this.solutions.push(new Solution(values["datas"][i]))
    }
}

$.ajax({
    url: 'api.php', // the data sent by the API is a valid JSON
    dataType: 'json',
    success: function(data, status) {
        console.log(data);
        for(i = 0; i < data.length; i++) {
            console.log(data[i]);
            var run = new Run(data[i])
            runs.push(run);
        }
    }
});

The console.log(data) before the for loop prints correctly all the datas recieved from the API, but the console.log(data[i]) prints only the first element of the array, and I can't understand why.

bastantoine
  • 582
  • 4
  • 21
  • TLDR: Always declare variables. – Jonas Wilms May 27 '19 at 07:43
  • Add `"use strict"` at the top of your javascript file, to turn on [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) so you get errors when you haven't declared a variable before using it. In for-statements you can use `let` instead of `var`: `for (let i=0; i < 10; ++i) { console.log(i); }` to keep the scope of the variable inside the for-statement. – some May 27 '19 at 08:02

1 Answers1

5

You are looping using a single global indexing variable i in multiple places.

Your first loop calls Run, which runs another loop to completion incrementing the i variable.

Start your loops declaring a local i each time:

for(var i=0;...)

Slawomir Chodnicki
  • 1,525
  • 11
  • 16