Skip to content
On this page

clone 深克隆

Hidden Title

基础用法:clone(data)

基础用法

说明

clone 用于深拷贝数据。传入普通对象、数组、日期、正则等常见数据时,会返回一份新的数据,避免直接修改原始引用;传入数组时还可以通过第二个参数控制重复复制次数。

调用形式

ts
clone(data)
clone(arrayData, times)
clone(refData)
clone(data)
clone(arrayData, times)
clone(refData)

参数说明

参数类型必填默认值说明
dataT | T[] | Ref<T>-要克隆的数据。如果传入 Vue ref,会先取出 ref.value 再克隆。
timesnumber1仅当 data 是数组时生效,表示把克隆后的数组内容重复追加多少次。

返回值

返回克隆后的数据。非数组会返回深拷贝结果;数组会返回一个新数组,并根据 times 重复展开数组内容。

常用场景

ts
const user = clone({ name: 'andy', extra: { id: 1 } })

const list = clone([1, 2, 3], 2)
// [1, 2, 3, 1, 2, 3]

const copied = clone(ref([{ id: 1 }]))
const user = clone({ name: 'andy', extra: { id: 1 } })

const list = clone([1, 2, 3], 2)
// [1, 2, 3, 1, 2, 3]

const copied = clone(ref([{ id: 1 }]))

注意事项

times 只对数组有意义;如果传入对象、数字、字符串等非数组数据,会忽略 times 并直接返回深拷贝结果。它适合处理业务数据复制,不建议用来复制 DOM、组件实例这类带运行时上下文的对象。

函数源码

clone

来源:packages/utils/src/base.ts

/**
 * 深拷贝数据;传入数组时可按次数重复展开。
 *
 * @param data 要克隆的数据。
 * @param times 当 `data` 是数组时的复制次数,默认 `1`。
 * @returns 克隆后的数据。
 *
 * @example
 * clone({ name: 'andy', info: { id: 1 } })
 *
 * @example
 * clone([1, 2, { name: 'andy' }], 2)
 * // => [1, 2, { name: 'andy' }, 1, 2, { name: 'andy' }]
 */
export function clone<T>(data: T[], times?: number): T[]
export function clone<T>(data: T, times?: number): T
export function clone<T>(data: T | T[], times = 1): T | T[] {
  const rawData = isRef(data) ? unref(data) : data
  // Check if the data is not an array
  if (!Array.isArray(rawData)) {
    // If not an array, return a deep clone of the data
    return cloneDeep(rawData) as T
  }
  const clonedData = cloneDeep(rawData) as T[]
  const result: T[] = []
  for (let i = 0; i < times; i++) {
    result.push(...clonedData)
  }
  return result
}

思云博智私有前端组件库