Angular 5数组去重函数报错:Property 'profile' does not exist on type 'void'
解决Angular 5中"Property 'profile' does not exist on type 'void'"报错
这个报错的核心原因是你在map的回调函数里用了普通的function,导致this的指向完全跑偏了——此时的this不再是你的Angular组件实例,而是map方法调用回调时的默认上下文(严格模式下会是undefined,也就是报错里的void类型),自然找不到profile属性。
给你几个实用的解决办法,按推荐程度排序:
1. 改用箭头函数(最推荐)
箭头函数会自动捕获外层作用域的this,也就是你的组件实例,这样就能正常访问this.profile了。另外,如果你只是要遍历数组做操作(比如修改emailArray),用forEach比map更合适——因为map的设计初衷是转换数组并返回新数组,你现在的场景不需要返回新数组,用forEach更高效:
this.contact.shared.emails.forEach(val => { if (this.profile.emails.indexOf(val.email_address) < 0) { this.emailArray.splice(/* 这里补全你的splice参数,比如要删除的索引、删除数量 */); } });
如果一定要用map(比如后续需要用到转换后的数组),同样用箭头函数,记得在回调里返回值:
this.contact.shared.emails.map(val => { if (this.profile.emails.indexOf(val.email_address) < 0) { this.emailArray.splice(/* 你的参数 */); } return val; // map必须返回值,否则会得到全是undefined的数组 });
2. 提前保存组件的this引用
在回调函数外面把组件的this存到一个变量里,比如self,然后在回调里用self代替this:
const self = this; this.contact.shared.emails.map(function(val) { if (self.profile.emails.indexOf(val.email_address) < 0) { self.emailArray.splice(/* 你的参数 */); } return val; });
3. 用bind绑定this
给回调函数绑定组件的this,确保调用时this指向正确:
this.contact.shared.emails.map(function(val) { if (this.profile.emails.indexOf(val.email_address) < 0) { this.emailArray.splice(/* 你的参数 */); } return val; }.bind(this));
总结一下,箭头函数是现在Angular项目里最常用的写法,既简洁又能避免this指向的坑,优先选这个方案就好。
内容的提问来源于stack exchange,提问作者cnak2
相关产品推荐
相关产品推荐

