发布于 1年前
JS 数组和对象的深浅克隆
// 数组和对象的深浅克隆
const clone = function clone() {
let target = arguments[0],
deep = false,
type,
isArray,
isObject,
ctor,
result,
treated = arguments[arguments.length - 1];
if (typeof target === "boolean") {
if (arguments.length === 1) return target;
deep = target;
target = arguments[1];
}
if (!Array.isArray(treated) || !treated.treated) {
treated = [];
treated.treated = true;
}
if (treated.includes(target)) return target;
treated.push(target);
type = toType(target);
isArray = isArrayLike(target);
isObject = isPlainObject(target);
if (target == null) return target;
ctor = target.constructor;
if (/^(regexp|date|error)$/i.test(type)) {
if (type === 'error') target = target.message;
return new ctor(target);
}
if (/^(function|generatorfunction)$/i.test(type)) {
return function proxy(...params) {
return target.call(this, ...params);
};
}
if (!isArray && !isObject) return target;
result = isArray ? [] : {};
each(target, function (copy, name) {
if (deep) {
result[name] = clone(deep, copy, treated);
return;
}
result[name] = copy;
});
return result;
};