// 自定义可以用于数组和对象上门的each方法
const each = function each(obj, callback) {
if (obj == null || typeof obj !== "object") throw new TypeError("obj must be an array/like-array/object");
if (typeof callback !== "function") callback = function () {
};
if (Array.isArray(obj)) {
let i = 0,
length = obj.length,
item;
for (; i < length; i++) {
item = obj[i];
if (callback.call(item, item, i) === false) break;
}
} else {
let keys = Object.keys(obj),
i = 0,
length = keys.length,
key,
item;
if (typeof Symbol !== "undefined") keys = keys.concat(Object.getOwnPropertySymbols(obj));
for (; i < length; i++) {
key = keys[i];
item = obj[key];
if (callback.call(item, item, key) === false) break;
}
}
return obj;
}
// 封装深浅合并
const merge = function merge() {
let options,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false,
treated = arguments[length - 1];
if (typeof target === "boolean") {
deep = target;
target = arguments[i] || {};
i++;
}
if(Array.isArray(treated) && treated.treated) {
length--;
} else {
treated = [];
treated.treated = true;
}
if(typeof target !== "object" && typeof target !== "function") target = {};
for(; i<length;i++){
options = arguments[i];
if(options ==null) continue;
if(treated.includes(options)) return options;
treated.push(options);
each(options, function(copy, name){
let copyIsArray = Array.isArray(copy),
copyIsObject = typeof copy === "object",
clone = target[name];
if(deep && copy && (copyIsArray || copyIsObject)) {
if(copyIsArray && !Array.isArray(clone)) clone = [];
if(copyIsArray && (typeof clone !== "object")) clone = {};
target[name] = merge(deep, clone, copy, treated);
} else if(copy !== undefined) {
target[name] = copy;
}
});
}
return target;
}
2021.7.22 封装数组和对象的深浅合并
最新推荐文章于 2024-09-14 18:52:56 发布