变量范围在d3中的javascript [英] variable scope in d3 javascript

查看:176
本文介绍了变量范围在d3中的javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用以下代码在全局变量中获取数据:

I want to get data in global variable by using the following code:

var data;
d3.json ( "file.json" , function(json) {
  data = json;
  console.log(data); //defined
});
console.log(data); //undefined

但问题是我只是在d3.json函数中定义了数据变量,它是未定义的。
我如何解决这个问题?

But the problem is that i just have data variable defined in d3.json function but out it is undefined. how can I solve this issue?

感谢

推荐答案

p>因为d3请求(如 d3.json )是异步的,所以最好的做法是在请求回调中包含所有依赖于外部请求的代码,确保此代码可以在执行之前访问数据。 从D3文档:当异步加载数据时,依赖于加载数据的代码应该通常存在于回调函数中。

Because d3 requests (like d3.json) are asynchronous, it's best practice to wrap all of the code dependent on your external request within the request callback, ensuring that this code has access to the data before executing. From the D3 docs: "When loading data asynchronously, code that depends on the loaded data should generally exist within the callback function."

所以一个选项是将所有代码放在回调函数中。如果您想将代码分成几部分,您还可以将请求中的响应传递到单独的函数,如下所示:

So one option is to put all of your code within the callback function. If you'd like to separate the code into parts, you can also pass the response from your request to a separate function, something like this:

function myFunc(data) {
    console.log(data);
}

d3.json('file.json', function (data) {
    var json = data;
    myFunc(json);
}

这篇关于变量范围在d3中的javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆