使用提取API JavaScript获取值数组 [英] Get an array of values using fetch api javascript

查看:84
本文介绍了使用提取API JavaScript获取值数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用访存api通过javascript读取txt文件.我想加载txt文件的内容,这些内容由数组中的新行分隔.

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.

文本文件:

A
B
C

我需要以下格式的文件:

I need it in the following format:

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

下面是我尝试的代码

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.

推荐答案

您可以通过分割换行符将文本响应转换为数组:

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));

这篇关于使用提取API JavaScript获取值数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆