为什么我的 D3.csv() 方法返回“未定义”

我只有一个 csv 文件,我正在尝试使用异步函数获取数据,但未定义。


<script>

    async function data(pathToCsv) {

        return await d3.csv(pathToCsv, function (data) {

            data.year = +data.year

            data.running_total = +data.running_total

            data.date = new Date(data.year, 0)

            return data

        })

    };

    let dataset = data('q3.csv');

    console.log(dataset.year);

</script>


富国沪深
浏览 180回答 2
2回答

守候你守候我

这里的问题是你的数据函数正在返回一个承诺,所以year从一个承诺对象访问将返回undefined,你需要await在调用你的时添加data function&nbsp;async function data(pathToCsv) {&nbsp; &nbsp; &nbsp; &nbsp; return await d3.csv(pathToCsv, function (data) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data.year = +data.year&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data.running_total = +data.running_total&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data.date = new Date(data.year, 0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return data&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp;};&nbsp; async function init() {&nbsp; &nbsp; &nbsp;let dataset = await data('q3.csv');&nbsp; &nbsp; &nbsp;// this should work now assuming you are using d3 function correctly as i'm not aware of d3 functions myself&nbsp; &nbsp; &nbsp;console.log(dataset.year);&nbsp;&nbsp; }&nbsp; init()

慕尼黑5688855

我解决了。<script>&nbsp; &nbsp; async function data(pathToCsv) {&nbsp; &nbsp; &nbsp; &nbsp; let dataset = await d3.csv(pathToCsv, function (d) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; d.year = +d.year&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; d.running_total = +d.running_total&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; d.date = new Date(d.year, 0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return d&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; return dataset&nbsp; &nbsp; };&nbsp; &nbsp; data('q3.csv').then(function(d) {&nbsp; &nbsp; &nbsp; &nbsp; d.forEach(function(p){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(p.date.getFullYear());&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; });</script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript