JavaScript Fetch API-将文本另存为对象? [英] JavaScript Fetch API - save text as object?
问题描述
我目前正在使用JavaScript中的访存API.我有一个要从sample.txt中读取的文本文件.我想从文本文件中抓取不同的行并将其保存在数组中,以便可以使用它.我一直在寻找如何将其另存为对象,但我想我一直在将代码用于JSON而不是文本.请提出任何建议吗?
I am currently working with the fetch API in JavaScript. I have a text file I'd like to read from called sample.txt. I would like to grab the different lines out of the text file and save it in an array so I can work with it. I've been searching for how to save it as an object, but I think I've been using the code for JSON and not for text. Please give any suggestions?
sample.txt
sample.txt
apple
banana
orange
grape
index.js
let fruitArray; //initialized new array
fetch('sample.txt') // fetch text file
.then((resp) => resp.text())
.then(data.split(/\r?\n/) = fruitArray)) //tried to assign each separate line as an element of fruitArray
预期产量
fruitArray = ['apple', 'banana', 'orange', 'grape'];
推荐答案
let fruitArray;
不会创建新的数组-为此,您实际上必须声明一个类似于[]
的数组.但是最好只在响应返回后才声明该数组,然后在需要时将其传递.
let fruitArray;
doesn't create a new array - you have to actually declare an array like []
for that. But it would be better to declare the array only once the response comes back, and then pass it around if needed.
.then
接受 function 作为参数,而不是普通代码块. .then
回调的第一个参数是前一个诺言的解析结果-这是完整的字符串.
.then
accepts a function as a parameter, not a plain code block. The first parameter of the .then
callback is the result of the resolution of the previous promise - which here is the full string.
分配(=
)时,左侧必须是变量(或属性).
When assigning (=
), the left hand side needs to be a variable (or a property).
fetch('sample.txt') // fetch text file
.then((resp) => resp.text())
.then(data => {
const fruitsArray = data.split(/\r?\n/);
})
这篇关于JavaScript Fetch API-将文本另存为对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!