csv文件讀取(v3&v5)

1.csv文件的讀取

1.1 d3.v3

d3.v3讀取一個文件,

d3.csv("csv1.csv", function(error1, data1) {
  // do something with the data

});

讀取多個文件,

d3.csv("csv1.csv", function(error1, data1) {
  d3.csv("csv2.csv", function(error2, data2) {
    // do something with the data
  });
});

讀取多個文件,還可以用queue.v3.min.js,然後可以這樣來寫,

d3.queue()
.defer(d3.csv, "file1.csv")
.defer(d3.csv, "file2.csv")
.await(function(error, data1, data2) {
    if (error) {
        console.error('Oh dear, something went wrong: ' + error);
    }
    else {
        //do something with the data
    }
});

1.2 d3.v5

d3.v5的讀取與之前有了改動,現在,我們可以按照如下方式進行讀取,

d3.csv('filename.csv')
    .then(function(data) {
        // data is now whole data set
        // draw chart in here!
        console.log(data);
  })
  .catch(function(error){
        // handle error   
  })

或者,可以這樣,

async function doThings() {
    const data = await d3.csv('filename.csv');
    // do whatever with data here
    
    console.log(data);
  
}

doThings();

讀取多個文件,可以這樣來寫

Promise.all([
    d3.csv("file1.csv"),
    d3.csv("file2.csv"),
    d3.csv("file3.csv"),
]).then(function(files) {
    // files[0] will contain file1.csv
    // files[1] will contain file2.csv
    // files[2] will contain file3.csv
    
}).catch(function(err) {
    // handle error here
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章