Skip to content

deepClone 深克隆 ​

17:43

说明 ​

$u.deepClone 通过 JSON 序列化与反序列化复制对象或数组,返回与原值内容相同、引用不同的副本;修改副本不会影响原值。

示例 ​

对象深克隆 ​

点击后克隆嵌套对象,并检查结果是否与原对象引用不同、JSON.stringify 内容一致。

查看源码
vue
<template>
    <ux-cell-group :border="false">
        <ux-cell-item title="原对象" :label="JSON.stringify(originalObj)" :arrow="false" :border-bottom="false" />
    </ux-cell-group>
    <ux-gap :height="8" />
    <ux-button size="small" type="primary" block text="克隆对象" @click="handleClone()" />
    <template v-if="clonedObj != null">
        <ux-gap :height="8" />
        <ux-cell-group :border="false">
            <ux-cell-item title="克隆对象" :label="JSON.stringify(clonedObj)" :arrow="false" />
            <ux-cell-item title="是否同一引用" :arrow="false">
                <ux-tag size="mini" :type="isSameRef ? 'error' : 'success'" :text="isSameRef ? '是' : '否'" />
            </ux-cell-item>
            <ux-cell-item title="内容是否相等" :arrow="false" :border-bottom="false">
                <ux-tag size="mini" :type="isDeepEqual ? 'success' : 'error'" :text="isDeepEqual ? '是' : '否'" />
            </ux-cell-item>
        </ux-cell-group>
    </template>
</template>

<script setup lang="ts">
import { $u } from '@/uni_modules/uview-pro-x';

const originalObj = ref<JsonObject>({
    name: '张三',
    age: 25,
    address: { city: '北京', district: '朝阳区' }
});
const clonedObj = ref<JsonObject | null>(null);
const isSameRef = ref<boolean>(false);
const isDeepEqual = ref<boolean>(false);

function handleClone(): void {
    clonedObj.value = $u.deepClone(originalObj.value);
    isSameRef.value = originalObj.value === clonedObj.value;
    isDeepEqual.value = JSON.stringify(originalObj.value) === JSON.stringify(clonedObj.value);
}
</script>

数组深克隆 ​

对含基础值与嵌套对象的数组做克隆,展示副本的 JSON 内容与原数组一致。

查看源码
vue
<template>
    <ux-cell-group :border="false">
        <ux-cell-item title="原数组" :label="JSON.stringify(originalArr)" :arrow="false" :border-bottom="false" />
    </ux-cell-group>
    <ux-gap :height="8" />
    <ux-button size="small" type="primary" block text="克隆数组" @click="handleCloneArray()" />
    <template v-if="clonedArr.length > 0">
        <ux-gap :height="8" />
        <ux-cell-group :border="false">
            <ux-cell-item title="克隆数组" :label="JSON.stringify(clonedArr)" :arrow="false" :border-bottom="false" />
        </ux-cell-group>
    </template>
</template>

<script setup lang="ts">
import { $u } from '@/uni_modules/uview-pro-x';

const originalArr = ref<any[]>([1, 2, { a: 3 }]);
const clonedArr = ref<any[]>([]);

function handleCloneArray(): void {
    clonedArr.value = $u.deepClone(originalArr.value);
}
</script>

API ​

参数 ​

参数说明类型默认值版本
obj需要克隆的对象或数组T--

返回值 ​

类型说明
T与入参同类型的全新副本

注意事项 ​

  • 实现为 JSON.parse(JSON.stringify(obj)),只有可 JSON 序列化的数据能被正确复制;函数与 undefined 会丢失。
  • Date 会被序列化成 ISO 字符串,RegExp、Map、Set 等特殊对象不会保留原类型。
  • 循环引用会让 JSON.stringify 抛错。
  • 返回的是全新引用,修改副本不会影响原对象或原数组。