如果array .prototype.slice()方法返回浅拷贝,为什么改变切片数组的值不会改变原始数组

If Array.prototype.slice() method returns shallow copy why does changing the value of sliced array does not change the original

本文关键字:数组 改变 切片 原始 为什么 slice prototype array 浅拷贝 返回 方法      更新时间:2023-09-26

Array.prototype.slice()方法文档中说

slice()方法返回一个数组部分的浅拷贝到一个新的数组对象中。

如果是这样的话,为什么修改array .prototype.slice()返回的数组不会改变原始值呢?

> a = [1, 2, 3]
[ 1, 2, 3 ]
> b = a.slice(0)
[ 1, 2, 3 ]
> b[0] = 4
4
> b
[ 4, 2, 3 ]
> a // the expected output should be the same as output of b if b is shallowcopy of a.
[ 1, 2, 3 ]
当试图修改数组a时,可能正在进行写时复制。如果是这样,从技术上讲,是否可以说Array.prototype.slice()确实返回浅拷贝?

a.slice的结果是一个新的数组,它不是指向初始变量的指针。