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

如何在JavaScript中动态嵌套数组?FilePond文件存入数组报错解决

问题分析与解决

错误原因

报错Uncaught TypeError: Cannot set properties of undefined (setting '0')的核心问题:

  • 你直接尝试给data_to_review['files'][index]赋值,但data_to_review['files']从未被初始化,此时它是undefined,自然无法设置数组索引。
  • 你把data_to_review声明为数组,却用字符串键(表单ID)给它添加属性,这不符合数组的使用逻辑,应该用对象存储这些键值对,再放进目标数组中。

修正后的代码

// 初始化符合期望结构的数组:[{ 表单字段, files: [] }]
let data_to_review = [{}];

$('.step:nth-child(1) .form-control').each(function(index, element){
   const fieldId = $(element).attr('id');
   if($(element).hasClass('required')) {
       nextstep = checkForm(fieldId);
   }
   // 给数组内的第一个对象添加表单字段键值对
   data_to_review[0][fieldId] = $(element).val(); 
});

$('.file_uploader').on('FilePond:addfile', function(e) {
     console.log('file added event', e);
     testData();
});

function testData() {
   let files = $('.file_uploader').filepond('getFiles');
   // 先初始化files数组,避免未定义报错
   if (!data_to_review[0].files) {
       data_to_review[0].files = [];
   }
   // 清空旧文件,确保每次都是最新的文件列表
   data_to_review[0].files = [];
   $(files).each(function (index) {
       data_to_review[0].files.push(files[index].file);
   });
   console.log(data_to_review);
}

关键修改点

  • 将data_to_review初始化为包含空对象的数组,完美匹配你期望的[{ files: [...] }]结构。
  • 表单字段赋值时,给数组内的对象(data_to_review[0])添加属性,而非直接给数组本身加属性。
  • 在testData中先确保data_to_review[0].files是数组,再用push方法添加文件(或直接重置为新数组后添加)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 13:03:35