上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* @param {null|boolean|number|string|Array|Object} obj1
* @param {null|boolean|number|string|Array|Object} obj2
* @return {null|boolean|number|string|Array|Object}
*/
var deepMerge = function(obj1, obj2) {
};
/**
* let obj1 = {"a": 1, "c": 3}, obj2 = {"a": 2, "b": 2};
* deepMerge(obj1, obj2); // {"a": 2, "c": 3, "b": 2}
*/
javascript 解法, 执行用时: 100 ms, 内存消耗: 55.7 MB, 提交时间: 2023-10-15 14:44:56
/**
* @param {any} obj1
* @param {any} obj2
* @return {any}
*/
var deepMerge = function(obj1, obj2) {
if (isObject(obj1) && isObject(obj2) && Array.isArray(obj1) == Array.isArray(obj2)) {
for (var key in obj2)
if (key in obj1) obj1[key] = deepMerge(obj1[key], obj2[key]);
else obj1[key] = obj2[key];
return obj1;
}
return obj2;
};
var isObject = function(obj) {
return typeof obj == "object" && obj != null;
}
/**
* let obj1 = {"a": 1, "c": 3}, obj2 = {"a": 2, "b": 2};
* deepMerge(obj1, obj2); // {"a": 2, "c": 3, "b": 2}
*/
typescript 解法, 执行用时: 96 ms, 内存消耗: 59.8 MB, 提交时间: 2023-10-15 14:44:31
type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };
function deepMerge(obj1: any, obj2: any): any {
if (typeof obj2 !== 'object' || obj2 === null) return obj2;
if (typeOf(obj1) !== typeOf(obj2)) return obj2;
for (const key in obj2) {
obj1[key] = deepMerge(obj1[key], obj2[key]);
}
return obj1;
};
function typeOf(obj: any): string {
return Object.prototype.toString.call(obj).slice(8, -1);
}
/**
* let obj1 = {"a": 1, "c": 3}, obj2 = {"a": 2, "b": 2};
* deepMerge(obj1, obj2); // {"a": 2, "c": 3, "b": 2}
*/
javascript 解法, 执行用时: 96 ms, 内存消耗: 55.6 MB, 提交时间: 2023-10-15 14:44:17
/**
* @param {any} obj1
* @param {any} obj2
* @return {any}
*/
const isNotObject = (val) => typeof val !== 'object' || val === null;
var deepMerge = function(obj1, obj2) {
// 判断是否是基本类型
if(isNotObject(obj1) || isNotObject(obj2)) return obj2;
// 判断两个是否都是数组
if(Array.isArray(obj1) !== Array.isArray(obj2)) return obj2;
// 通过 for in 替代 Object.keys 与 forEach 优化性能
for(const key in obj2) {
obj1[key] = deepMerge(obj1[key], obj2[key])
}
return obj1;
};
var deepMerge2 = function(obj1, obj2) {
var isObject = (obj) => {
return Object.prototype.toString.call(obj) === '[object Object]'
}
if (Array.isArray(obj1) && Array.isArray(obj2)){
let myIndex = 0;
let newArr = [];
obj2.forEach((num,index) => {
newArr[myIndex++]=deepMerge(obj1[index],num);
})
return newArr.concat(obj1.slice(myIndex));
}
if (isObject(obj1) && isObject(obj2)){
let result = {};
let keyArray = [...new Set(Object.keys(obj1).concat(Object.keys(obj2)))];
keyArray.forEach((key) => {
result[key] = deepMerge(obj1[key],obj2[key]);
})
return result;
}
if (obj1 === undefined){
return obj2;
}
if (obj2 === undefined){
return obj1;
}
return obj2
};
/**
* let obj1 = {"a": 1, "c": 3}, obj2 = {"a": 2, "b": 2};
* deepMerge(obj1, obj2); // {"a": 2, "c": 3, "b": 2}
*/