小记一波百度面试基础编程题。要求手写,回来害怕错误,专门又写了一遍。由于正则容易出错,手写时用的字符串截取的方式来实现的。见笑了~~ 捂脸
// 已知 obj = {
a: {
b: {
c: {
d: {
e: 5
}
}
}
}
}
实现一个方法 getValue(obj, 'a.b.c.d') 取到 obj.a.b.c.d 的值
实现方式
1. 正则匹配法
function getValue(obj, path) {
if (typeof path !== 'string') throw new Error(`参数传入类型错误`);
const reg = /^(\w+)((\.\w+)*)$/;
const matchResult = reg.exec(path);
// debugger;
if (!matchResult) {
return obj;
}
const prefix = matchResult[1];
const lastFix = (matchResult[2] || '.').substr(1);
if (obj[prefix]) {
return getValue2(obj[prefix], lastFix)
} else {
throw new Error(`取值不正确`);
}
}
2. 字符串截取法
function getValue(obj, path) {
if (typeof path !== 'string') throw new Error(`参数传入类型错误`);
const splitFlag = path.indexOf('.');
if (splitFlag < 0) return obj[path];
const prefix = path.substring(0, splitFlag);
const lastFix = path.substring(splitFlag + 1);
// debugger;
if (!lastFix) return obj;
if (obj[prefix]) {
return getValue(obj[prefix], lastFix);
} else {
throw new Error(`取值不正确`);
}
}
自测
const obj = {
a: {
b: {
c: {
d: {
e: 5
}
}
}
}
}
const v1 = getValue(obj, 'a.b.c.d'); // {e: 5}
const v2 = getValue(obj, 1); // error `参数传入类型错误`
const e1 = getValue(obj, 'a.s.x.t'); // error `取值不正确`
const v3 = getValue(obj, 'a'); // {b: { ... }}
才浅学疏,若您有什么优秀的方式,please tell me。
愿娘子相离之后重梳婵鬓,美扫蛾眉;巧呈窈窕之姿,选聘高官之主;解怨释结,更莫相憎;一别两宽,各生欢喜。 一一 唐朝《放妻书》