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
相关产品推荐
相关产品推荐

