Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Javascript slice method return a shallow copy?

In a Mozilla developer translated Korean lang says 'slice method' returns a new array copied shallowly.

so I tested my code.

var animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

var t = animals.slice(2,4);
console.log(t);

t[0] = 'aaa';
console.log(t);
console.log(animals);

but, If slice method returns shallow array, the animals array should be changed with ['ant', 'bison', 'aaa', 'duck', 'elephant'].

Why is it shallow copy?

like image 366
SeongUk Mun Avatar asked Dec 10 '17 11:12

SeongUk Mun


People also ask

Does slice make a deep copy Javascript?

slice is a shallow-copy method, which means it can't copy an object deeply.

What slice will do in Javascript?

The slice() method returns selected elements in an array, as a new array. The slice() method selects from a given start, up to a (not inclusive) given end. The slice() method does not change the original array.

Does slice return a new array Javascript?

slice does not change original array it return new array but splice changes the original array.

Is Javascript slice destructive?

slice() is a method of Array Object and String Object. It is non-destructive since it return a new copy and it doesn't change the content of input array.


1 Answers

strings are primitive types in JavaScript, so you will get a new array with new strings inside.

Your test array should be an array of objects:

var animals = [{name: 'ant'}, {name: 'bison'}, {name: 'camel'}, {name: 'duck'}, {name: 'elephant'}];

var t = animals.slice(2,4);
console.log(t);

t[0].name = 'aaa';
console.log(t);
console.log(animals);
like image 107
klugjo Avatar answered Oct 12 '22 08:10

klugjo