/**
* 替换字符串中字符
* @param target {string} 目标字符串
* @param keys {array} 需要替换的字符
* @param str {string} 替换完后的字符
*/
function replaceString(target, keys, str) {
let temp = target;
keys.forEach(function (item) {
temp = temp.replace(item, str)
});
return temp;
};
/**
* 将对象键值key抽离为一个数组
* @param obj {object} 目标对象
*/
function objectKeytoArray(obj) {
let temp = [];
for (let key in obj) {
temp.push(key);
};
return temp;
};
/**
* 判断数据类型
* @param target {any} 检测目标
*/
function judgeDataType(target) {
let typeMessage = Object.prototype.toString.apply(target);
typeMessage = replaceString(typeMessage, ["[", "]"], "");
return typeMessage.split(" ")[1];
};
/**
* 深克隆对象
* @param obj {object} 目标对象
*/
function cloneObject(obj) {
let temp = {};
for (let key in obj) {
temp[key] = obj[key];
};
return temp;
};
/**
* 清空对象的所有属性值
* @param obj {object} 目标对象
*/
function clearObjectProperty(obj) {
let type = judgeDataType(obj);
if (type !== "Object") return console.error("目标应为对象 (fn judgeDataType)");
if (objectKeytoArray(obj).length === 0) return console.error("目标不能是空对象 (fn judgeDataType)");
let temp = cloneObject(obj);
for (let key in temp) {
switch (judgeDataType(temp[key])) {
case "Array":
temp[key] = [];
break;
case "String":
temp[key] = "";
break;
case "Object":
clearObjectProperty(temp[key])
break;
case "Number":
temp[key] = 0;
break;
default:
temp[key] = undefined;
};
};
return temp;
};
let targetData = {
a: [1, 2, 3, 4, 5],
b: "仍然是好的",
c: {
key: "确实是的"
},
d: /abc/
};
console.log(clearObjectProperty(targetData))
console