【问题标题】:VueJS .filter changes content of array when it should notVueJS .filter 不应该更改数组的内容
【发布时间】:2021-09-06 23:00:21
【问题描述】:

所以我要做的是根据另一个数组的内容过滤一个数组,这就是我拥有的代码。

private get filteredArray() {
  const filteredArray = this.unfilteredArray;
  console.log(this.unfilteredArray);

  filteredArray = this.unfilteredArray.filter(
    (p) => this.filteredNumbers.includes(p)
  );
  return filteredArray;
}

例如,我们有两个带有值的数组

this.unfilteredarray = ["1", "2", "4", "3"]
this.filteredNumbers = ["2"]

this.filteredNumbers 从多选框中获取值,因此这里用户选择了2,为此,函数返回的项目是数组filteredArray,其值为"2"。但是,当我随后选择另一个数字进行过滤时,this.filteredNumbers 看起来像 ["2", "3"],那么当我期望返回 2 and 3 时,我仍然只能返回值为 "2"filteredArray。这似乎是因为在console.log 上,我可以看到,当我第二次选择filterNumber 时,unfilteredArray 只剩下"2" 的值,而它仍应保留其所有原始数字 1- 4.我在这里缺少什么或者我应该以其他方式做到这一点?

编辑:正确答案的后续问题 因此,如果我有一个对象,它的所有道具中有 3 个不同的数组,我想将它们全部过滤,然后返回对象本身及其过滤后的数组。有点像这样,但是这个 ofc 不起作用,因为它会弄乱原始数组。或者我需要 3 个不同的 get 吗?

private get filteredObject() {
   this.object.unfilteredArray.filter(
    (p) => this.filteredNumbers.includes(p)
  );
   this.object.unfilteredArrayTwo.filter(
    (p) => this.filteredNumbers.includes(p)
  );
   this.object.unfilteredArrayThree.filter(
    (p) => this.filteredNumbers.includes(p)
  );
  return object;
}

【问题讨论】:

    标签: javascript arrays vue.js filter


    【解决方案1】:

    const filteredArray = this.unfilteredArray; 不会按照您的意愿克隆数组,它只是引用将在您这样做时被覆盖的数组:

      filteredArray = this.unfilteredArray.filter(
        (p) => this.filteredNumbers.includes(p)
      );
    

    这意味着filteredArray this.unfilteredArray 指的是相同的数据。

    为了避免这种情况,只需返回过滤后的数组并创建一个临时数组:

    private get filteredArray() {
       return this.unfilteredArray.filter(
        (p) => this.filteredNumbers.includes(p)
      );
      
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-25
      • 2018-12-02
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 2020-07-19
      • 2022-10-05
      • 1970-01-01
      相关资源
      最近更新 更多