Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在不同javascript数组中排序json响应_Javascript_Angular - Fatal编程技术网

在不同javascript数组中排序json响应

在不同javascript数组中排序json响应,javascript,angular,Javascript,Angular,使用Angular2 我得到json响应,其中有一个操作/移动列表 如果动作类型为移动,则将其分配给移动前进数组 如果动作类型为战斗,则将其分配给动作数组 publicmovesforward=[] 公共行动=[] ngOnInit() { this.userData.actions.forEach(function(entry) { switch(entry.type) { case "m

使用Angular2

我得到json响应,其中有一个操作/移动列表

  • 如果动作类型为移动,则将其分配给移动前进数组
  • 如果动作类型为战斗,则将其分配给动作数组

    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”

  • 我对使用管道不感兴趣,因为它只在一个组件中一次性使用

如何在我的foreach中访问我的主要类变量?

只要使用
()=>
而不是
函数()
(如果您使用的是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)