val*_*lis 1 javascript fetch-api
我正在使用 fetch api 通过 javascript 读取 txt 文件。我想加载由数组中的新行分隔的 txt 文件的内容。
文本文件:
A
B
C
Run Code Online (Sandbox Code Playgroud)
我需要以下格式:
arr = ["A", "B", "C"]
Run Code Online (Sandbox Code Playgroud)
下面是我试过的代码
var arr = []
fetch('file.txt')
.then(function(response) {
return response.text();
}).then(function(text) {
arr.push(text)
console.log(text)
});
console.log(arr)
Run Code Online (Sandbox Code Playgroud)
没有任何内容添加到我的数组中,但是文本文件中的数据会打印在控制台上。
您可以通过拆分换行符将文本响应转换为数组:
function fetchData() {
return fetch('data.txt')
.then(response =>
response.text().then(text => text.split(/\r|\n/)));
}
fetchData().then(arr => console.log(arr));Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11301 次 |
| 最近记录: |