对象是否在 javascript 深拷贝或浅拷贝中推入数组? [英] Do objects pushed into an array in javascript deep or shallow copy?

查看:34
本文介绍了对象是否在 javascript 深拷贝或浅拷贝中推入数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不言自明的问题...当在 javascript 中的数组上使用 .push() 时,推入数组的对象是指针(浅)还是实际对象(深)不管类型.

Pretty self evident question...When using .push() on an array in javascript, is the object pushed into the array a pointer (shallow) or the actual object (deep) regardless of type.

推荐答案

这取决于你在推动什么.对象和数组作为指向原始对象的指针推送.数字或布尔值等内置原始类型作为副本推送.因此,由于对象不会以任何方式复制,因此它们没有深拷贝或浅拷贝.

It depends upon what you're pushing. Objects and arrays are pushed as a pointer to the original object . Built-in primitive types like numbers or booleans are pushed as a copy. So, since objects are not copied in any way, there's no deep or shallow copy for them.

这是一个显示它的工作片段:

Here's a working snippet that shows it:

var array = [];
var x = 4;
let y = {name: "test", type: "data", data: "2-27-2009"};

// primitive value pushes a copy of the value 4
array.push(x);                // push value of 4
x = 5;                        // change x to 5
console.log(array[0]);        // array still contains 4 because it's a copy

// object reference pushes a reference
array.push(y);                // put object y reference into the array
y.name = "foo";               // change y.name property
console.log(array[1].name);   // logs changed value "foo" because it's a reference    

// object reference pushes a reference but object can still be referred to even though original variable is no longer within scope
if (true) {
    let z = {name: "test", type: "data", data: "2-28-2019"};
    array.push(z);
}

console.log(array[2].name);   // log shows value "test" since the pointer reference via the array is still within scope

这篇关于对象是否在 javascript 深拷贝或浅拷贝中推入数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆