Get an array of values using fetch api javascript

不想你离开。 提交于 2019-12-31 04:08:23

问题


I am using fetch api to read a txt file via javascript. I want to load the contents of the txt file which are separated by new line in an array.

Text file:

A
B
C

I need it in the following format:

arr = ["A", "B", "C"]

Below is the code I tried

var arr = []
fetch('file.txt')
  .then(function(response) {
    return response.text();
  }).then(function(text) {
arr.push(text)
console.log(text)

    });
  console.log(arr)

Nothing gets added to my array, however the data from the text file gets printed on the console.


回答1:


You can convert the text response to an array by splitting on newline characters:

function fetchData() {
    return fetch('data.txt')
            .then(response =>
                response.text().then(text => text.split(/\r|\n/)));
}

fetchData().then(arr => console.log(arr));


来源:https://stackoverflow.com/questions/51548012/get-an-array-of-values-using-fetch-api-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!