从 CSV 加载 D3 中特定列时未定义的数据



我正在尝试从csv文件中读取数据,我想将每列的数据存储在数组中,如下面的代码所示。我得到的我不知道如何解决的问题是所有值都在括号内定义,但是一旦我尝试处理其他数组,数据是未定义的。关于出了什么问题的任何想法?我的 D3 版本是 v3。

<script>
var computerid = [];
var timestamp = [];
var percentage = [];
d3.csv("cpu-util.csv", function(data) {
    for (var i = 0; i < data.length; i++) {
        timestamp[i] = data[i].timestamp;
        computerid[i] = data[i].Computer_ID; 
        percentage[i] = data[i].Percentage;
        console.log(computerid[i]); //prints value
        console.log(timestamp[i]);
        console.log(percentage[i]);
    }
});
console.log(computerid[1]); //here, it prints undefined although inside the loop it prints values

csv 文件的一部分:

Computer_ID、时间戳、值、百分比

1, 01-07-11 0:00, 0.8, 8

您的 CSV 数据必须采用正确的格式。有一些不必要的空格使得难以解析,因为它在标头名称中包含空格,在此基础上它将属性名称保留在对象中。

CPU util.csv应该是

Computer_ID,timestamp,value,Percentage
1,01-07-11 0:00,0.8,8

此外.js d3 解析保留标头标签的数据。 因此computerid数组应使用数据的 Computer_ID 属性填充。因此,您的代码应该是这样的:

<script>
   var timestamp = [],
       computerid = [],
       percentage = [];
 d3.csv("cpu-util.csv", function(data) {
   console.log(data); //see the data structure
    for (var i = 0; i < data.length; i++) {
        timestamp[i] = data[i].timestamp; //use the property names.
        computerid[i] = data[i].Computer_ID; 
        percentage[i] = data[i].Percentage;
        console.log(computerid[i]);
        console.log(timestamp[i]);
        console.log(percentage[i]);
    }
     console.log(computerid[0]); //this will appear as it is within the function and 
                                 //the array is filled by the time this line is run
  });
  console.log(computerid[0]); //this will be undefined due to the asynchronous nature of javascript. 
                              //This line of code runs before the for loop within the function
</script>

如果您看到控制台日志,由于 javascript 的异步性质,console.log(computerid[0])将首先出现在日志中,然后再出现在函数中的其他三个日志中。您可以通过多种方式链接函数,使其使用 Async/Await 或 Promise 进行同步。

此外,d3.js将所有信息解析为字符串。因此,需要使用函数将诸如Percentage之类的数字值转换为数字数据类型。请记住这一点。

最新更新