题目(2018-11-19)
有时候我们需要访问一个对象较深的层次,但是如果这个对象某个属性不存在的话就会报错,例如:
var data = { a: { b: { c: 'ScriptOJ' } } }
data.a.b.c // => scriptoj
data.a.b.c.d // => 报错,代码停止执行
console.log('ScriptOJ') // => 不会被执行
请你完成一个safeGet
函数,可以安全的获取无限多层次的数据,一旦数据不存在不会报错,会返回undefined
,例如:
var data = { a: { b: { c: 'ScriptOJ' } } }
safeGet(data, 'a.b.c') // => scriptoj
safeGet(data, 'a.b.c.d') // => 返回 undefined
safeGet(data, 'a.b.c.d.e.f.g') // => 返回 undefined
console.log('ScriptOJ') // => 打印 ScriptOJ
实现
循环
首先想到的方法就是利用循环实现,每次循环都进行一次判断,判断属性是否存在,存在继续,不存在跳出
最早完成的代码:
const safeGet = (data, path) => {
let result = undefined;
if (!data || !path) {
return result
}
const tempArr = path.split('.');
for (let i = 0; i < tempArr.length; i++) {
const key = tempArr[i];
if (data[key]) {
result = data[key];
data = data[key];
} else {
result = undefined;
break;
}
}
return result;
};
这段代码至少有两个可以优化的地方:
- 没有必要声明
result
这个变量,直接使用data
即可 -
for
循环内部不必break
,直接return
跳出函数即可
所以优化之后:
const safeGet = (data, path) => {
if (!data || !path) {
return undefined
}
const tempArr = path.split('.');
for (let i = 0; i < tempArr.length; i++) {
const key = tempArr[i];
if (data[key]) {
data = data[key];
} else {
return undefined;
}
}
return data;
};
递归
除了使用循环,当然也可以递归调用函数来实现:
const safeGet = (data, path) => {
const key = path.split('.')[0];
const restPath = path.slice(2);
if (!data[key]) {
return undefined;
}
if (!restPath) {
return data[key]
}
return safeGet(data[key], restPath)
};
try...catch
看看了讨论区,受了一些启发,还可以使用try...catch
实现
const safeGet = (data, path) => {
const tempArr = path.split('.');
try {
while (tempArr.length > 0) {
data = data[tempArr.shift()]
}
return data;
} catch (e) {
return undefined;
}
};
reduce
还可以使用ES6中强大的reduce
实现,非常简洁:
const safeGet = (data, path) => {
if (!data || !path) {
return undefined
}
const tempArr = path.split('.');
// 注意初始值是给谁赋值
return tempArr.reduce((total, current) = > {
return (total && total[current]) ? total[current] : undefined
}, data)
};
要注意的一点,
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
参数initialValue
是初始值,是赋值给total
的值,不要搞错。