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!
在那里,您拥有了! 如果您需要的只是天真的克隆,请不要遍历数组以克隆它们!