-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
简易深克隆, 没考虑Date、Regexp、Error
- 确定你的原始数据对象中的属性值没有
function或者undefined, 你可以使用常规的JSON.parse(JSON.stringify())进行深克隆。
/**
* 简易深度克隆
* @param {*} originVal - 原始数据
*/
const deepClone = originVal => {
if (typeof originVal !== 'object') {
return originVal;
}
const hasDeepCloned = originVal.constructor === Object ? {} : [];
for (const key in originVal) {
if (originVal.hasOwnProperty(key)) {
const val = originVal[key];
hasDeepCloned[key] = typeof val === 'object' ? deepClone(val) : val;
}
}
return hasDeepCloned;
}
const originData = {
name: 'thunder',
favor: [{
one: 'ball'
}]
};
const newData = deepClone(originData);
newData.name = 'modified data';
newData.favor[0].one = 'modified ball';
console.log(originData); // { name: 'thunder', favor: [ { one: 'ball' } ] }
console.log(newData); // { name: 'modified data', favor: [ { one: 'modified ball' } ] }Metadata
Metadata
Assignees
Labels
No labels