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

查看:30
本文介绍了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?

谢谢

推荐答案

因为 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天全站免登陆