[英]Array.filter() and reference of objects filtered
如果我们在一个对象数组上应用array.filter
函数,结果数组是否包含对它从第一个数组过滤的对象的引用?
does the resultant array hold reference to the objects it filtered from the first array
结果数组是否保存对它从第一个数组过滤的对象的引用
Yes, they're the same objects, filter
doesn't clone them.是的,它们是相同的对象,
filter
器不会克隆它们。 It's just like doing this doesn't clone an object:这就像这样做不会克隆一个对象:
const a = {id: 1, value: "one"};
const b = a;
a.value = a.value.toUpperCase();
console.log(b.value); // "ONE" <== In caps
Live Example with filter
:带
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; }
Note that "ONE"
is in all caps in the object, regardless of which array you get the object reference from.请注意,无论您从哪个数组获取对象引用,
"ONE"
都是对象中的所有大写字母。
just an example that it does, check @TJ Crowder's answer links只是一个例子,检查@TJ Crowder的答案链接
const arr = [{a:1}, {a:2}, {a:2}]; const newArr = arr.filter(v => va < 3); newArr[0].a = 5; console.log(arr); console.log(newArr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.