qappleh / Interview

我是追梦赤子心,公众号「深圳湾码农」的作者,某上市集团公司高级前端开发,深耕前端领域多年,每天攻破一道题,带你从0到1系统构建web全栈完整的知识体系!
https://github.com/qappleh/Interview
1.14k stars 95 forks source link

Day404: 实现一个获取对象任意属性的方法?(字节) #407

Open qappleh opened 2 years ago

qappleh commented 2 years ago
const getAttribute = (object /*目标对象*/,attribute /*目标属性*/, defaultValue /*默认值*/)

示例:
const obj = {a: {b: {c: 100}}, d:[{f: 'abc'}]};
getAttribute(obj, 'a.b.c', 0) === 100
getAttribute(obj, 'a.b.e', 'default') === 'default'
getAttribute(obj, 'd.0.f') === 'a.b.c'
Moushudyx commented 2 years ago

思来想去,还是直接上来的简单,加了一丢丢脑补:

const getAttribute = (obj, attr, defaultValue = undefined) => {
  if(typeof attr === 'number' || typeof attr === 'symbol') {
    // 数字或 Symbol 属性
    // 题目没讲,视为合法
    if(attr in obj) return obj[attr];
  } else if (attr && typeof attr === 'string') {
    // 字符串属性
    // 题目没讲,那么空的 attr 视为不合法
    let temp = obj;
    for(const a of attr.split('.')){ // 按“.”分割
      if(!(a in temp)) return defaultValue;
      else temp = temp[a];
    }
    return temp;
  } else return defaultValue; // 属性不合法或没有这个属性则返回默认值
};

测试用的代码:

{
  const getAttribute = (obj, attr, defaultValue = undefined) => {
    if(typeof attr === 'number' || typeof attr === 'symbol') {
      // 数字或 Symbol 属性
      // 题目没讲,视为合法
      if(attr in obj) return obj[attr];
    } else if (attr && typeof attr === 'string') {
      // 字符串属性
      // 题目没讲,那么空的 attr 视为不合法
      let temp = obj;
      for(const a of attr.split('.')){ // 按“.”分割
        if(!(a in temp)) return defaultValue;
        else temp = temp[a];
      }
      return temp;
    } else return defaultValue; // 属性不合法或没有这个属性则返回默认值
  };
  // 示例
  const obj = {a: {b: {c: 100}}, d:[{f: 'abc'}], 1: 1, y: undefined};
  console.log(
    getAttribute(obj, 'a.b.c', 0) === 100,
    getAttribute(obj, 'a.b.e', 'default') === 'default',
    getAttribute(obj, 'd.0.f') === 'abc',
    // 数字属性
    getAttribute(obj, 1) === 1,
    // 使用 in 关键字因此不会忽略值为 undefined 的属性
    getAttribute(obj, 'y', null) === undefined,
  )
}

回过头来看看,我写的这个还是有问题,没有考虑到属性名中可能出现.(英文句点)的情况, ~题目没讲就当不存在咯~ ;将typeof attr缓存一下也许更容易阅读 ~(用isNumber之类的类型守卫可以更好看)~ ,懒得改了。