JavaScript: simple array cloning

That is pretty easy and I guess obviously and known to all the advanced JavaScript hackers, but I was searching a bit for it and now I am using it constantly. For where there is no clone() method for arrays, you can simply use:


    var arr = [1,2,3,4];
    // slice() does the cloning for us. Doesn't handle nested arrays/objects!
    var cloned = arr.slice(0);
    // Now you can modify arr without fear of cloned being modified too.
    arr[2] = "Other value";

RSS feed for comments on this post · TrackBack URL

Leave a Comment