简体   繁体   English

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

[英]Array reference passed to a function is lost when array.filter is applied

The idea of this pattern is to manage different arrays. 这种模式的想法是管理不同的阵列。 When user clicks on an option it selects/deselects it and option's value is pushed into/filtered from the corresponding array. 当用户单击某个选项时,它会选择/取消选择该选项,然后将选项的值推入/从相应的数组中过滤掉。

I am trying to write the universal method that will manage the array it was called with, at the moment it works fine with pushing values but doesn't work with filtering. 我正在尝试编写一种通用方法来管理被调用的数组,目前它在推入值时可以正常工作,但不适用于过滤。

Angular Component Methods (doesn't work) 角组件方法(无效)

 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;
      })
    }
}

Angular Component Methods (works if referenced to array directly) 角组件方法(如果直接引用数组,则可以使用)

 potatoesArray = [];

 manageOptions($event, testingArray) {

  ...

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

Note 注意

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

Template implementation 模板实施

<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>

Remove this from the template implementation 删除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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM