应用array.filter时,传递给函数的数组引用将丢失

时间:2017-05-12 23:30:18

标签: javascript angular typescript

这种模式的想法是管理不同的数组。当用户点击某个选项时,它会选择/取消选择该选项,并将选项的值从相应的数组推入/过滤。

我正在尝试编写一个通用方法来管理它所调用的数组,目前它可以正常工作并推送值但不适用于过滤。

角度组件方法(不起作用)

 potatoesArray = [];

 manageOptions($event, testingArray) {

  const checkExistence = (array, value) => {
    return !(array.indexOf(value) >= 0)    
  }

  if ($event) {
    // SPAN value
    const optionValue = $event.target.innerText;      

    // Push if value isn't in array
    if (checkExistence(testingArray, optionValue)) {
      testingArray.push(optionValue);      

    // 'Remove' the value if it's in array  
    } else {
      testingArray = testingArray.filter((option) => {
        return option != optionValue;
      })
    }
}

角度组件方法(如果直接引用数组,则有效)

 potatoesArray = [];

 manageOptions($event, testingArray) {

  ...

    } else {
      this.potatoesArray = testingArray.filter((option) => {
        return option != optionValue;
      })
    }
}

注意

console.log(testingArray === this.potatoesArray) // true

模板实施

<div class="option" (click)='manageOptions($event, this.potatoesArray)'>
  <span>OPTION 1</span>
  ...                              
</div>

<div class="option" (click)='manageOptions($event, this.potatoesArray)'>
  <span>OPTION 2</span>                              
  ...
</div>

<div class="option" (click)='manageOptions($event, this.potatoesArray)'>
  <span>OPTION 3</span>                              
  ...
</div>

1 个答案:

答案 0 :(得分:2)

从模板实现中删除this

<div class="option" (click)='manageOptions($event, potatoesArray)'>
  <span>OPTION 1</span>
  ...                              
</div>

<div class="option" (click)='manageOptions($event, potatoesArray)'>
  <span>OPTION 2</span>                              
  ...
</div>

<div class="option" (click)='manageOptions($event, potatoesArray)'>
  <span>OPTION 3</span>                              
  ...
</div>