这种模式的思想是管理不同的数组。当用户单击某个选项时,它会选择/取消选择该选项,并且选项的值将被插入/从相应的数组中过滤。
我正在尝试编写通用方法来管理调用它的数组,目前它可以很好地推送值,但不能用于过滤。
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/