使用JavaScript克隆数组

Believe it or not, there are reasons we use JavaScript frameworks outside of animations and those sexy accordions that people can't do without. The further you get into high-powered JavaScript applications (assuming you're creating true web applications, not websites), the more the need for basic JavaScript functionalities; i.e. JavaScript utilities that have nothing to do with DOM. One of those basic utilities is the ability to clone an array. Quite often I see developers iterating over array items to create their clone; in reality, cloning an array can be as easy as a slice!

信不信由你,我们有理由在动画和那些人们无法缺少的性感手风琴之外使用JavaScript框架。 您越深入了解功能强大JavaScript应用程序(假设您正在创建真正的Web 应用程序 ,而不是网站 ),则对基本JavaScript功能的需求就越大; 即与DOM无关JavaScript实用程序。 这些基本实用程序之一是克隆阵列的功能。 我经常看到开发人员遍历数组项以创建其克隆。 实际上,克隆数组就像slice一样容易!

JavaScript (The JavaScript)

To clone the contents of a given array, all you need to do is call slice, providing 0 as the first argument:

要克隆给定数组的内容,您需要做的就是调用slice ,并提供0作为第一个参数:


var clone = myArray.slice(0);


The code above creates clone of the original array; keep in mind that if objects exist in your array, the references are kept; i.e. the code above does not do a "deep" clone of the array contents. To add clone as a native method to arrays, you'd do something like this:

上面的代码创建原始数组的副本; 请记住,如果对象存在于数组中,则保留引用; 即上面的代码没有对数组内容进行“深层”克隆。 要将clone作为本机方法添加到数组,请执行以下操作:


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


And there you have it! Don't iterate over arrays to clone them if all you need is a naive clone!

在那里,您拥有了! 如果您需要的只是天真的克隆,请不要遍历数组以克隆它们!

翻译自: https://davidwalsh.name/javascript-clone-array

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值