[tag]:记录|js|deep copy [create]:2019-10-25
const _toString = Object.prototype.toString;
function _isObject(val) {
return _toString.call(val) === '[object Object]';
}
function _isArray(val) {
return _toString.call(val) === '[object Array]';
}
function _forEach(val, fn) {
if (val === null || typeof val === 'undefined') {
return;
}
// 对象与数组选用不同的循环方式,因为for in循环性能比较不好
if (_isArray(val)) {
for (let i = 0; i < val.length; i++) {
fn && fn(val[i], i);
}
} else if (_isObject(val)) {
for (let key in val) {
fn && fn(val[key], key);
}
} else {
fn && fn(val, 0);
}
}
function deepCopy(newObj, copyObj) {
_forEach(copyObj, function(val, key) {
if (_isObject(val)) {
newObj[key] = deepCopy({}, val);
} else if (_isArray(val)) {
newObj[key] = deepCopy([], val);
} else {
newObj[key] = val;
}
});
return newObj;
}