You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

fetch读取txt文件时出现lines.split is not a function报错怎么解决

错误原因
  • 核心问题是调用split()方法的目标对象类型错误:你代码中声明的lines初始值为空数组[],split()是仅字符串类型拥有的方法,数组不存在该方法,因此触发类型错误。
  • 你需要拆分的是fetch请求返回的txt文件纯文本内容,对应内层then回调的入参response,你错误选择了操作lines变量而非返回的文本内容。
  • 自定义变量使用了JS内置构造函数名Array,容易引发命名冲突,建议更换为语义化名称如lineArr。
修复后的代码
<script>
fetch("questions.txt")
  .then(response => {
    console.log('请求状态码:', response.status);
    return response.text();
  })
  .then(textContent => {
    console.log('读取到的txt内容:', textContent);
    // 对返回的文本按换行符拆分
    const lineArr = textContent.split("\n");
    // 可选:过滤掉空行
    // const lineArr = textContent.split("\n").filter(item => item.trim() !== '');
    console.log('按行拆分后的数组:', lineArr);
    // 后续使用数组的逻辑请写在该回调内
  })
  .catch(err => {
    console.error('处理过程出错:', err);
  });
</script>

说明:优化为Promise链式调用写法,避免了嵌套回调问题,新增异常捕获逻辑方便定位请求、处理阶段的错误

内容的提问来源于stack exchange,提问作者Constantina Christodoulou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 12:06:06