How to copy an array in Javascript

An array can be copied in javascript using the slice command, the objects in the array are passed by reference.

Syntax:


var tab2 = tab1.slice();

The slice command takes 2 parameters to generate a subset of the current tab, if no parameters are passed a clone of the current array is returned.

Example:

This example creates an array with the values a, b, c and d. The array is copied in the variable tab2. The first value from the first array is modified. Both array are written in the logs, the first array has the modifed value and the second one doesn't.

var tab1 = ['a', 'b', 'c', 'd'];
var tab2 = tab1.slice();

tab1[0] = '1';

console.log('tab1:' );
console.log( tab1);

console.log('tab2:' );
console.log(tab2);

The output will be:


> "tab1:"
> Array ["1", "b", "c", "d"]
> "tab2:"
> Array ["a", "b", "c", "d"]


References:

Array slice

Recent Comments