繁体   English   中英

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

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

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

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

角组件方法(无效)

 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>

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