Does Javascript slice method return a shallow copy?

前端 未结 3 1755
耶瑟儿~
耶瑟儿~ 2020-12-04 01:51

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

so I tested my code.

var animals = [\'ant\'         


        
相关标签:
3条回答
  • 2020-12-04 02:13

    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);

    0 讨论(0)
  • 2020-12-04 02:17

    slice does not alter the original array. It returns a shallow copy of elements from the original array.

    Elements of the original array are copied into the returned array as follows:

    For object references (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.

    For strings, numbers and booleans (not String, Number and Boolean objects), slice copies the values into the new array. Changes to the string, number or boolean in one array do not affect the other array. If a new element is added to either array, the other array is not affected.(source)

    In your case the the array consists of strings which on slice would return new strings copied to the array thus is a shallow copy. In order to avoid this use the object form of array.

    0 讨论(0)
  • 2020-12-04 02:25

    The slice method doesn't change the original array or string. It only cuts a portion of the original string or array and returns it as a copy. For more understanding of it, kindly check this video below: https://youtu.be/mUH8hPQfMbg [Slice method made easy for absolute beginners]

    0 讨论(0)
提交回复
热议问题