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

标签 javascript angular typescript

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

我正在尝试编写通用方法来管理调用它的数组,目前它可以很好地推送值,但不能用于过滤。

Angular 组件方法(不起作用)

 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 组件方法(如果直接引用数组则有效)

 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>

关于javascript - 应用 array.filter 时,传递给函数的数组引用会丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43947732/

相关文章:

javascript - 如何在等待函数结束的Javascript中创建加载器?

javascript - 如何在 Angular 7 中创建一个函数

javascript - 将tinymce显示成html代码

html - Angular/CSS 表格格式。 Div 对象阻止表格格式化

ios - ionic2 - 提供的参数与调用目标的任何签名都不匹配

javascript - 使用 jquery 动画背景颜色

angular - 在从服务中检索到所有数据之前不要加载页面

angularjs - Angular-cli无法正确安装

javascript - 一个数组/对象的强类型多个变量

typescript - 如何只加载一次字体? (TS/三.JS)