I had a need to clone an array with JavaScript. There appears to be a number of different ways to do it, including writing your own function. All of these solutions below will just create a reference to the original array:
var newArray = myArray.slice(0); var newArray = myArray.concat([]); var newArray = clone(myArray);
A popular answer using jQuery is the following:
var newArray = jQuery.extend(true, {}, myArray);
However, this solution will return an object and you cannot get the length of an object like you can an array.
To return an array, we change the curly braces to square brackets like so:
var newArray = jQuery.extend(true, [], myArray);
This is the solution that works.
Continue Reading
Hi I'm Nick Bartlett and thanks for visiting my blog. I'm not much of a writer; many of my posts are short and to the point while others are meant to be a reference for myself and other web developers.