简体   繁体   中英

Array length remains 0 even though I push 'objects' to it

I have a little piece of code that reads some ajax (this bit works) from a server.

var self = this;
var serverItems = new Array();
var playersOnlineElement = $("#playersOnline");

function DataPair(k, v) {
    this.key = k;
    console.log("new datapair: " + k + ", " + v);
    this.value = v;
}

DataPair.prototype.getKey = function() {
    return this.key;
}

DataPair.prototype.getValue = function() {
    return this.value;
}

$.getJSON("http://127.0.0.1", function(data) {
    $.each(data, function(key, val) {
        var pair = new DataPair(key, val);
        self.serverItems.push(pair);
    });
});

console.log(serverItems.length); //Problem is here
for (var i = 0; i < serverItems.length; i = i + 1) {
    var dpair = serverItems[i];
    if (dpair.getKey() === "playersOnline") {
        self.playersOnlineElement.text("Players Online: " + dpair.getValue());
    }
}

The datapair and the JSON get loaded but when they are pushed to the array it doesn't seem to work. I tried with self.serverItems and just serverItems because netbeans showed me the scope of the variables being good if I used just serverItems but I am a bit confused as to why this doesn't work. Can anyone help me?

I put in comments where the error is. serverItems.length is 0 even though when debugging in a browser in the DOM tree it has an array serverItems with all the data inside.

Assumingly this serverItems is in another scope and not the one I am calling when I want to get the length?

add this code into the success part, since its asynchronous...

for (var i = 0; i < serverItems.length; i = i + 1) {
    var dpair = serverItems[i];
    if (dpair.getKey() === "playersOnline") {
        self.playersOnlineElement.text("Players Online: " + dpair.getValue());
    } 

to...

$.getJSON("http://127.0.0.1", function(data) {
    $.each(data, function(key, val) {
        var pair = new DataPair(key, val);
        self.serverItems.push(pair);

      for (var i = 0; i < serverItems.length; i = i + 1) {
        var dpair = serverItems[i];
        if (dpair.getKey() === "playersOnline") {
            self.playersOnlineElement.text("Players Online: " + dpair.getValue());
        } 
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM