在不同javascript数组中排序json响应
使用Angular2 我得到json响应,其中有一个操作/移动列表在不同javascript数组中排序json响应,javascript,angular,Javascript,Angular,使用Angular2 我得到json响应,其中有一个操作/移动列表 如果动作类型为移动,则将其分配给移动前进数组 如果动作类型为战斗,则将其分配给动作数组 publicmovesforward=[] 公共行动=[] ngOnInit() { this.userData.actions.forEach(function(entry) { switch(entry.type) { case "m
- 如果动作类型为移动,则将其分配给移动前进数组李>
- 如果动作类型为战斗,则将其分配给动作数组
publicmovesforward=[]代码>
公共行动=[]代码>
我的问题是,ngOnInit() { this.userData.actions.forEach(function(entry) { switch(entry.type) { case "move": this.movesForward.push(entry); break; case "fight": this.actions.push(entry); break; } }); }
在内部函数中,我无法访问此函数中的公共变量foreach
TypeError:无法读取未定义的属性“movesBack”
- 我对使用管道不感兴趣,因为它只在一个组件中一次性使用
()=>
而不是函数()
(如果您使用的是TS或ES6)
或者在ES5中
ngOnInit()
{
this.JwtService.userData.zone.actions.forEach((function (entry){
switch(entry.type)
{
case "move":
this.movesForward.push(entry);
break;
case "fight":
this.actions.push(entry);
break;
}).bind(this)
});
}
只需使用()=>
而不是函数()
(如果您使用的是TS或ES6)
或者在ES5中
ngOnInit()
{
this.JwtService.userData.zone.actions.forEach((function (entry){
switch(entry.type)
{
case "move":
this.movesForward.push(entry);
break;
case "fight":
this.actions.push(entry);
break;
}).bind(this)
});
}
正确的。另一种解决方案是使用
.bind(this)
。对。另一种解决方案是使用.bind(this)
。