Interview icon indicating copy to clipboard operation
Interview copied to clipboard

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

Open qappleh opened this issue 4 years ago • 1 comments

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'

qappleh avatar Sep 27 '21 10:09 qappleh

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

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之类的类型守卫可以更好看)~ ,懒得改了。

Moushudyx avatar Oct 08 '21 07:10 Moushudyx