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

如何将结构化字符串转换为带属性的JavaScript对象数组

代码错误分析与修复

核心错误点

  1. 拆分逻辑完全错误:你先把整个文本按换行符拆成了单行数组redovi,然后用map遍历每一行,又对单个行文本执行split('\n')——单个行里根本没有换行符,所以解构出来的address、phone、course全是undefined。
  2. 未按数据分组处理:每个学生的信息是固定4行一组(姓名→地址→电话→课程),你没有按这个分组规则批量处理,而是逐行处理,导致无法匹配对应字段。
  3. 未处理空行:文本末尾可能存在空行,会干扰分组逻辑。

修复后的完整代码

let button = document.getElementById('get-text-btn');
let textArea = document.getElementById('my-text-area');
let loader = document.getElementById('loader'); // 补上之前缺失的loader变量

button.addEventListener('click', function () {
  loader.style.display = 'inline-block';
  fetch('https://v-dresevic.github.io/Advanced-JavaScript-Programming/data/students.txt')
    .then(function (response) {
      if (response.status !== 200) {
        throw Error('Error while reading file.');
      }
      return response.text();
    })
    .then(function (text) {
      // 1. 拆分文本为行数组,过滤掉空行(含仅空格的行)
      const lines = text.split('\n').filter(line => line.trim() !== '');
      const students = [];

      // 2. 按每4行一组遍历,组装学生对象
      for (let i = 0; i < lines.length; i += 4) {
        students.push({
          name: lines[i].trim(),
          address: lines[i+1].trim(),
          phone: lines[i+2].trim(),
          course: lines[i+3].trim()
        });
      }

      console.log(students);
      // 可选:把结果格式化后显示到文本框
      textArea.value = JSON.stringify(students, null, 2);
    })
    .catch(function (err) {
      textArea.innerHTML = 'Fetch problem: ' + err.message;
    })
    .finally(function () {
      loader.style.display = 'none';
    });
});
<button id="get-text-btn">Get Data</button>
<div id="loader"></div>
<textarea id="my-text-area" rows="30"></textarea>

关键修复说明

  • 先通过filter过滤掉空行,避免分组时出现索引越界或无效数据
  • 使用for循环按步长4遍历数组,每次取连续4个元素对应学生的4个字段
  • 给每个字段加上trim(),避免文本中可能存在的首尾空格

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 17:02:38