先张贴下源码:
function cloneBuffer(buffer, isDeep) {
if (isDeep) {
return buffer.slice()
}
const length = buffer.length
const result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length)
buffer.copy(result)
return result
}
在源码中,当 isDeep
为 true
,即要深拷贝时,使用的是 buffer.slice
方法。
但是关于 slice
方法,文档有如下描述:
Returns a new Buffer that references the same memory as the original
链接:https://nodejs.org/docs/latest-v13.x/api/buffer.html#buffer_buf_slice_start_end
也即 slice
所返回的新 Buffer
和原 Buffer
指向的是同一块内存。
在和 TypedArray.slice
的对比中更有如下描述:
While TypedArray#slice() creates a copy of part of the TypedArray, Buffer#slice() creates a view over the existing Buffer without copying.
链接:https://nodejs.org/docs/lates...
清楚说明了 slice
是 without copying
的,为什么 lodash
会用作深拷贝呢?
slice()
可以对数组的第一层级进行深拷贝, 第一层级数据类型只限基本数据类型。