JavaScript Fetch API - save text as object?

江枫思渺然 提交于 2019-12-25 01:48:10

问题


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

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

Expected Output

fruitArray = ['apple', 'banana', 'orange', 'grape'];

回答1:


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


来源:https://stackoverflow.com/questions/50383280/javascript-fetch-api-save-text-as-object

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