小記一波百度面試基礎編程題。要求手寫,回來害怕錯誤,專門又寫了一遍。由於正則容易出錯,手寫時用的字符串截取的方式來實現的。見笑了~~ 捂臉
// 已知 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。
願娘子相離之後重梳嬋鬢,美掃蛾眉;巧呈窈窕之姿,選聘高官之主;解怨釋結,更莫相憎;一別兩寬,各生歡喜。 一一 唐朝《放妻書》