javascript tutorial - Copying array by value in JavaScript - javascript - java script - javascript array



Problem:

When copying an array in JavaScript to another array?

Solution 1:

var arr1 = ['a','b','c'];
var arr2 = arr1;
arr2.push('d');  //Now, arr1 = ['a','b','c','d']

click below button to copy the code. By JavaScript tutorial team

Solution 2:

Use this:

var newArray = oldArray.slice();
click below button to copy the code. By JavaScript tutorial team

Basically, the slice() operation clones the array and returns the reference to the new array. Also note that: For references, strings and numbers (and not the actual object), slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.

Primitives such as strings and numbers are immutable so changes to the string or number are impossible.

Solution 3:

Three types of elements

Elements can be: literal values, literal structures, or prototypes.

// Literal values (type1)
var booleanLiteral = true;
var numberLiteral = 1;
var stringLiteral = 'true';

// Literal structures (type2)
var arrayLiteral = [];
var objectLiteral = {};

// Prototypes (type3)
var booleanPrototype = new Bool(true);
var numberPrototype = new Number(1);
var stringPrototype = new String('true');
var arrayPrototype = new Array();
var objectPrototype = new Object(); # or "new function () {}"
click below button to copy the code. By JavaScript tutorial team

From these elements we can create three types of arrays.

// 1) Array of literal-values (boolean, number, string) 
var type1 = [true, 1, "true"];

// 2) Array of literal-structures (array, object)
var type2 = [[], {}];

// 3) Array of prototype-objects (function)
var type3 = [function () {}, function () {}];
click below button to copy the code. By JavaScript tutorial team

Solution 4:

var arr2 = arr1.slice()
click below button to copy the code. By JavaScript tutorial team

This copys the array from the starting position 0 through the end of the array.

Solution 5:

An alternative to slice is concat, which can be used in 2 ways. The first of these is perhaps more readable as the intended behaviour is very clear:

var array2 = [].concat(array1);
click below button to copy the code. By JavaScript tutorial team

The second method is:

var array2 = array1.concat();
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Copying array by value in JavaScript