Pregunta

I have this code in Javascript:

var words = [];

d3.json("myFile.json", function(data) {
    words = data.words;
    console.log(words);  //Log output to console
});

console.log(words);  //Log output to console

The first console.log(words); shows an array of seven objects. But the second console.log(words); shows an empty array. So it looks like words outside of the d3.json function is not the same as words inside that function.

I also have tried to use console.log(window.words); outside of the function and it still shows an empty array.

How can I get the data that I have read from myFile.json in the d3.json function, outside of that function?

¿Fue útil?

Solución

d3.json is an asynchronous function. That means that the code you pass is not executed immediately, but as a callback after the request for the JSON file returns. That is, a network request is sent for the file, but the normal flow of execution continues.

The console.log(words); outside d3.json is simply executed before the call returns and the array is populated.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top