当我们要进行多级的对象的嵌套的时候,如果我们要是进行一层层的判断,我们会发现我们将大部分的时间花费在了判断上面,这样并不利于代码的可读性,举一个例子
a = aaa.bbb.ccc.vvv.ddd.ggg.www
在上面的操作我们必须要确保aaa
,aaa.bbb
,aaa.bbb.ccc
,aaa.bbb.ccc.vvv
....不为undefined
,这样的话,程序的判断就会有很多,我们现在封装了一个方法
// target :是你要判断到哪一级
// res:是你的元数据
// flag:判断你是用什么方式传入的 当flag 为true的时候 ,是.的形式,否则为[]形式
const objectIsNull = (target, res, flag) => {
let finnalResult = {};
let result = [];
finnalResult.location = '';
let currenTarget = "";
let num = 0;
const IterationObject = (target, currenTarget, res, num) => {
let targetValue = 0;
let temp;
// 当flag 为true的时候 ,是.的形式
if (flag) {
temp = target.split(".");
} else {
let processData = target.replace(/\[/g, "").replace(/\"/g, "");
temp = processData.split("]");
temp.pop();
}
targetValue = temp.length;
temp.length = num + 1;
currenTarget = temp.join(".");
if (!getValue(res, currenTarget)) {
result.push(false);
finnalResult.location = currenTarget;
return;
}
num++;
if (num < targetValue) {
IterationObject(target, currenTarget, res, num);
}
result.push(true);
return;
};
IterationObject(target, currenTarget, res, 0, flag);
finnalResult.result = result.shift();
return finnalResult;
};
具体的示例如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script>
// const obj = {a: {b: {c: {name: 'json'}}}};
const getValue = function(res, string) {
const stringArr = string.split(".");
const length = stringArr.length;
for (let key = 0; key < length; key++) {
if (!res[stringArr[key]]) {
return undefined;
}
res = res[stringArr[key]];
}
return res;
};
let res1 = { 禁忌: { 禁忌: { 禁忌: { 禁忌: {} } } } };
let target1 = '["禁忌"]["禁忌"]["禁忌"]["禁忌"]["禁忌"]';
let res = { a: { b: { c: {} } } };
let target = "a.b.c";
const objectIsNull = (target, res, flag) => {
let finnalResult = {};
let result = [];
finnalResult.location = '';
let currenTarget = "";
let num = 0;
const IterationObject = (target, currenTarget, res, num) => {
let targetValue = 0;
let temp;
// 当flag 为true的时候 ,是.的形式
if (flag) {
temp = target.split(".");
} else {
let processData = target.replace(/\[/g, "").replace(/\"/g, "");
temp = processData.split("]");
temp.pop();
}
targetValue = temp.length;
temp.length = num + 1;
currenTarget = temp.join(".");
if (!getValue(res, currenTarget)) {
result.push(false);
finnalResult.location = currenTarget;
return;
}
num++;
if (num < targetValue) {
IterationObject(target, currenTarget, res, num);
}
result.push(true);
return;
};
IterationObject(target, currenTarget, res, 0, flag);
finnalResult.result = result.shift();
return finnalResult;
};
let aaa = objectIsNull(target, res, true);
console.log(aaa);
let bbb = objectIsNull(target1, res1, false);
console.log(bbb);
</script>
</head>
</html>
返回结果:
jieguo
网友评论