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

如何在JavaScript二维数组中设置对象/属性?AngularJS代码报错求助

解决AngularJS二维数组赋值的"undefined index"错误

首先,咱们先拆解你遇到的问题:你想要构建一个能支持$scope.conditions.condition_set[$parent.$index][$index].response = "somevalue"格式的二维数组,但当前代码里有两个关键错误导致了报错:

1. 循环内重复重置外层数组

你的代码里每次循环都执行$scope.conditions.condition_set = [];,这会把之前已经创建的子数组全部清空,完全无法累积数据,相当于每次循环都从零开始。

2. 错误的子数组赋值语法

$scope.conditions.condition_set[key][].message = "hi there"这种写法是无效的——[]在这里不能用来直接赋值,你需要先确保子数组存在,然后要么向其中添加元素,要么明确指定索引来赋值对象。


修正后的代码示例

先看最基础的正确写法,假设你是想用循环的索引作为外层数组的键:

// 先初始化整个结构,必须放在循环外面!
$scope.conditions = {
  condition_set: []
};

result.forEach(function(item, outerIndex) { 
  // 先检查当前外层索引对应的子数组是否存在,不存在就初始化
  if (!$scope.conditions.condition_set[outerIndex]) {
    $scope.conditions.condition_set[outerIndex] = [];
  }
  
  // 方式1:往子数组里添加新对象(完美适配ng-repeat里的$index场景)
  $scope.conditions.condition_set[outerIndex].push({
    message: "hi there",
    response: "somevalue" // 直接加上你需要的response属性
  });

  // 方式2:如果需要指定子数组的具体索引赋值(比如固定位置)
  // $scope.conditions.condition_set[outerIndex][0] = {
  //   message: "hi there",
  //   response: "somevalue"
  // };
});

如果你的key是自定义的非连续值(比如字符串或者非顺序数字),更推荐把condition_set改成对象(避免数组出现空位导致ng-repeat异常):

$scope.conditions = {
  condition_set: {} // 改成对象而非数组
};

result.forEach(function(key) { 
  // 确保当前key对应的子数组存在
  if (!$scope.conditions.condition_set[key]) {
    $scope.conditions.condition_set[key] = [];
  }
  
  $scope.conditions.condition_set[key].push({
    message: "hi there",
    response: "somevalue"
  });
});

为什么这样能解决问题?

  • 把外层数组/对象的初始化放在循环外面,避免每次循环清空之前的结果;
  • 先检查并初始化子数组,确保不会访问undefined的索引;
  • 使用push()或者明确索引赋值的方式,替代错误的[]直接赋值语法,保证数组结构完全符合你的需求。

这样你之后就能正常使用$scope.conditions.condition_set[$parent.$index][$index].response来访问或赋值了。

内容的提问来源于stack exchange,提问作者noobie-php

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:04:20