最近项目上有个事情很困扰。项目是两方合作的,我方提供页面,他方提供数据。数据结构定义写的很清楚。本地测试都是没有问题,到了快要上线,联调的时候页面总是有卡死现象,查询日志后发现数据结构时而正确时而缺斤少两。
所以前端一定要保持对后端传来的数据规范性的怀疑。
那么如何在较复杂的数据结构中减少引用错误呢?
一般方法
层层判断
if(a && a.b && a.b.c){
// xxxxx
}
ES2020
可选链操作符,非常方便,但是兼容性不好
if(a?.b?.c){
// xxxx
}
自定义函数
函数返回内容:目标数据 | undefined | null ;
function safeGet(obj, path) {
if (obj === undefined || obj === null) return obj; // 未找到数据或为null,执行终断
if (!path) return obj; // 索引路径为空,执行结束
indexList = path.split(/\[|\]|\.|,/g).filter((e) => e && e.trim());
nextIndex = indexList.splice(1).join();
const nextObj = Reflect.get(obj, indexList[0]);
return safeGet(nextObj, nextIndex);
}
测试
// 数据结构和引用链匹配
const testObj1 = [
{
a: {
b: {
c: [
{},
{
d: [{ e: "right" }],
},
],
},
},
},
];
const result1 = safeGet(testObj1, "[0].a.b.c[1].d[0].e");
console.log(result1); // right
// 数据结构异常
const testObj2 = [
{
a: {
b: {
c:null
},
},
},
];
const result2 = safeGet(testObj2, "[0].a.b.c[1].d[0].e");
console.log(result2); // undefined
目前测试暂未出现异常,有更好的方式欢迎一起探讨。