Array.filter()和过滤对象的引用

时间:2018-11-15 11:29:35

标签: javascript arrays array-filter

如果我们在对象数组上应用"abc"函数,结果数组是否保留对其从第一个数组过滤掉的对象的引用?

2 个答案:

答案 0 :(得分:0)

仅举一个例子,请查看@ T.J。人群答案链接

    const arr = [{a:1}, {a:2}, {a:2}];

    const newArr = arr.filter(v => v.a < 3);

    newArr[0].a = 5;

    console.log(arr);
    console.log(newArr);

答案 1 :(得分:0)

  

结果数组是否保留对其从第一个数组过滤的对象的引用

是的,它们是相同的对象,filter不会克隆它们。就像这样做不会克隆对象:

const a = {id: 1, value: "one"};
const b = a;
a.value = a.value.toUpperCase();
console.log(b.value); // "ONE" <== In caps

带有filter的实时示例:

const a = [
  {id: 1, value: "one"},
  {id: 2, value: "two"},
  {id: 3, value: "three"}
];
const b = a.filter(entry => entry.id % 2);
a[0].value = a[0].value.toUpperCase();
console.log(a);
console.log(b);
.as-console-wrapper {
  max-height: 100% !important;
}

请注意,"ONE"位于对象的所有大写字母中,无论您从哪个数组中获取对象引用。