简体   繁体   English

Javascript中的局部变量与全局变量

[英]local vs global variable in Javascript

I have this code in Javascript: 我在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); 第一个console.log(words); shows an array of seven objects. 显示了七个对象的数组。 But the second console.log(words); 但是第二个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. 因此,看起来d3.json函数外部的words与该函数内部的words

I also have tried to use console.log(window.words); 我也尝试过使用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? 我如何在d3.json函数中获取从myFile.json中读取的数据?

d3.json is an asynchronous function. d3.json是一个异步函数。 That means that the code you pass is not executed immediately, but as a callback after the request for the JSON file returns. 这意味着您传递的代码不会立即执行,而是作为对JSON文件请求返回后的回调 That is, a network request is sent for the file, but the normal flow of execution continues. 即,发送了针对该文件的网络请求,但是正常的执行流程仍在继续。

The console.log(words); console.log(words); outside d3.json is simply executed before the call returns and the array is populated. 在调用返回并填充数组之前,只需执行d3.json外部即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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