我正在尝试将 .txt deocument 转换为数组。
文档中有名称,结构如下:
Name1
Name2
Name3
程序必须读取行,输出应该是
["Name1","Name2","Name3"].
我在网上找遍了,但大多数解决方案只涉及 node.js,我无法在需要该软件的计算机上安装它,或者一些我不理解的复杂 xmlhttp 代码。我只是在寻找一个简单的解决方案。
有人可以帮忙吗?
最佳答案
由于您不会使用节点,我假设您是在浏览器上运行代码。来自 <input type="file"/>
的文件
<html>
<input type="file" id="inputFile">
<script>
const inputFile = document.querySelector('#inputFile');
inputFile.addEventListener('change', () => {
const fileReader = new FileReader();
fileReader.onload = e => {
const array = e.target.result.split('\n');
console.log(array);
};
fileReader.readAsText(inputFile.files[0], 'UTF-8');
});
</script>
</html>
关于javascript - 我如何将 .txt 文档转换为 JavaScript 中的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68897469/