我一直在寻找使用 d3.csv 函数从 CSV 收集数据并返回一行的方法,以便我可以在不同函数的“for 循环”中使用它来设置多少for 循环应该运行的时间。
下面是我的代码的主要布局,显示了相关的两个函数。
通过我的“createLights 函数”,我希望它调用“getData”函数返回特定行,以便“createLights”函数中的“lightPol”变量运行 for 循环来生成随机 SVG 方 block 。
但是,由于javascript和d3的异步性,我一直无法做到这一点。我是 d3 的初学者,所以不太了解它的某些功能。
<...>
function createLights(tempHeight) {
var lightPol = getData(1);;
console.log(lightPol); //debug data to be retuend
for (m = 0; m < lightPol; m++) { //amount egenrated
tempHeight = tempHeight * 1.5;
var window_height = Math.floor(Math.random() * 30) + 0; //pos rand
var window_space = Math.floor(Math.random() * 20) + 10; //pos rand
window_space = window_space + i;
var shape1 = document.createElementNS(svgNS, "rect"); //to create a circle/rct
//attributes
document.getElementById("mysvg2").appendChild(shape1);
}
}
function getData(pollution) {
//console.log(pollution);//see if polution varible read right
var dataset = [];
d3.csv("py/Resources.csv", function(data) {
dataset = data.map(function(d) {
return +d.value;
});
//reutrn dataset[pollution]''
});
return 5; //placeholder of function, the d3 should generate a number and return it.
}
最佳答案
d3.csv("py/Resources.scv") 回调中的data
将保存您需要的所有内容。我不知道您的具体代码结构,但您可以首先采用简单的方法进行绘图以及回调中的所有内容
这意味着 CreateLight 应该位于 GetData 内部
关于javascript - d3.csv : using specific row data to use in a for loop argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47884912/