// JS对象深度合并
export function deepMerge() {
var src; var copyIsArray; var copy; var name; var options; var clone
var target = arguments[0] || {} // 这里说明第一个参数其实空着也是可以的
var i = 1
var length = arguments.length
var deep = true // 多层深复制的参数在这里
// Handle a deep copy situation
if (typeof target === 'boolean') {
deep = target
// skip the boolean and the target
target = arguments[ i ] || {}
i++
}
// Handle case when target is a string or something (possible in deep copy)
if (typeof target !== 'object' && !typeof target === 'function') {
target = {}
}
if (i === length) {
target = this
i--
}
for (; i < length; i++) {
// Only deal with non-null/undefined values
if ((options = arguments[ i ]) != null) {
// Extend the base object
for (name in options) {
src = target[ name ]
copy = options[ name ]
// Prevent never-ending loop
if (target === copy) {
continue
}
// Recurse if we're merging plain objects or arrays
if (deep && copy && (copy instanceof Object || (copyIsArray = (copy instanceof Array)))) {
if (copyIsArray) {
copyIsArray = false
clone = src && src instanceof Array ? src : []
} else {
clone = src && src instanceof Object ? src : {}
}
// Never move original objects, clone them
target[ name ] = deepMerge(deep, clone, copy) // 多层深复制的递归调用在这里
// Don't bring in undefined values
} else if (copy !== undefined) {
target[ name ] = copy
}
}
}
}
// Return the modified object
return target
}
// 使用方法
deepMerge(source, target)
本文地址:https://zhangyexing.cn/theme_2/bbsInfo/20210618132501
转载请著名出处,谢谢!
欢迎交流
QQ:419268793