问题
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