JavaScript : Array assignment creates reference not copy

本文深入探讨了JavaScript中数组赋值时产生的引用问题而非值拷贝,并提供了几种有效的方法来实现数组的深拷贝,避免了因引用导致的意外数据变动。
  • JavaScript : Array assignment creates reference not copy

29 May 2015

Consider we have an array var a = [1,2,3,4]; and we assign var b = a; then b not a copy of a, b is a pointer to a. So if you make any changes on b will have effect on a as well. Here is an example.

var a = [1,2,3,4]; var b = a; var b.pop(); console.log(b); // [1, 2, 3] console.log(a); // [1, 2, 3] 

so if you really want a copy of a you need to use .slice method.

var a = [1,2,3,4]; var b = a.slice(0); var b.pop(); console.log(b); // [1, 2, 3] console.log(a); // [1, 2, 3, 4] 

JavaScript doesn’t have a clone method for array, so if you really want, you can define yourself on Array but its not highly recommended.

Array.prototype.clone = function(){ return this.slice(0) } 

Now you can call .clone on any Array type.

var a = [1,2,3,4]; var b = a.clone(); var b.pop(); console.log(b); // [1, 2, 3] console.log(a); // [1, 2, 3, 4] 

I recommend to keep this in mind when ever you are dealing with JavaScript Array’s, else you might facing some unexpected behaviour and wonder why it happens.

Happy coding.

If you particularly enjoy my work, I appreciate donations via PayPal.

转载于:https://www.cnblogs.com/fdyang/p/8005624.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值