1

I'm trying to load some text from a file, split it by \n and push every line into an array:

var entries = new Array();
$( document ).ready(function() {
    loadFile(); 
    console.log(entries.length) // Result: 0
});

function loadFile(){
    $.get('file.txt', function(data) {
        console.log(data); // my file is shown
        var lines = data.split("\n");
        $.each(lines, function(key, value) {
            entries.push(value);
        });

    }, 'text'); 
}

I can see the contents of my file in the console, so the file is being loaded, but my array remains empty, its length is 0.

Why the lines won't be pushed into my array?

Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181

1 Answers1

1

$.get is asynchronous function so you should show the length in callback after getting the response data :

var entries = new Array();
$( document ).ready(function() {
    loadFile();
});

function loadFile(){
    $.get('file.txt', function(data) {
        console.log(data); // my file is shown

        var lines = data.split("\n");
        $.each(lines, function(key, value) {
            entries.push(value);
        });

        console.log(entries.length) // that will return the true length

    }, 'text'); 
}

Check How do I return the response from an asynchronous call?.

Hope this helps.

Community
  • 1
  • 1
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101