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

Angular2中arrayDrag数组undefined问题:无法存入10个数字

问题分析与解决方案

嘿,这个问题我太熟悉啦!你遇到的undefined错误根本不是数组初始化的问题,而是回调函数里的this指向不对导致的。

问题根源

你在调用this.gridApi.forEachNodeAfterFilterAndSort时用了普通的function作为回调,这个回调函数里的this并不指向你的组件实例,而是指向forEachNodeAfterFilterAndSort方法的执行上下文,所以this.arrayDrag自然就变成undefined了。

三种解决方案(按推荐程度排序)

1. 使用箭头函数(最简洁推荐)

箭头函数会自动绑定外层作用域的this,也就是你的组件实例,这样就能正确访问this.arrayDrag了:

rowDragEnd(event) {
  let max = 0;
  this.arrayDrag = new Array(); // 或者 new Array(10) 都可以
  this.gridApi.forEachNodeAfterFilterAndSort((node) => {
    if (max < 10) {
      this.arrayDrag.push(node.data.point);
      console.log('add', node.data.point);
      max += 1;
    }
  });
}

2. 提前保存组件的this到变量

在回调函数外面先把组件的this存到一个变量里(比如self),然后在回调里用这个变量访问数组:

rowDragEnd(event) {
  let max = 0;
  this.arrayDrag = new Array();
  const self = this; // 保存组件的this
  this.gridApi.forEachNodeAfterFilterAndSort(function(node) {
    if (max < 10) {
      self.arrayDrag.push(node.data.point); // 用self代替this
      console.log('add', node.data.point);
      max += 1;
    }
  });
}

3. 用bind绑定this

把回调函数的this手动绑定到组件实例上:

rowDragEnd(event) {
  let max = 0;
  this.arrayDrag = new Array();
  this.gridApi.forEachNodeAfterFilterAndSort(function(node) {
    if (max < 10) {
      this.arrayDrag.push(node.data.point);
      console.log('add', node.data.point);
      max += 1;
    }
  }.bind(this)); // 绑定组件的this到回调函数
}

额外说明

你之前对arrayDrag的初始化(不管是new Array()还是new Array(10))都是没问题的,只要解决了this指向的问题,push操作就能正常执行啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:17:25