【问题标题】:how to get the following output of the code snippet?如何获得代码片段的以下输出?
【发布时间】:2020-12-19 08:30:26
【问题描述】:

我在一次采访中被问到这个问题。如何解决这个问题?提到了对象和控制台语句。我没有得到如何实现函数 findPath?

【问题讨论】:

标签: javascript object output


【解决方案1】:

class Obj {
  constructor() {
    this.data = {
      a: {
        b: {
          c: 12
        }
      }
    };
  }

  findPath = (str) => {
    let sol = this.data;
    for (let key of str.split(".")) {
      sol = sol[key];
      if (!sol) {
        return undefined;
      }
    }
    return JSON.stringify(sol);
  };
}

let obj = new Obj();
console.log(obj.findPath("a.b.c"));
console.log(obj.findPath("a.b"));
console.log(obj.findPath("a.b.d"));
console.log(obj.findPath("a.c"));
console.log(obj.findPath("a.b.c.d"));
console.log(obj.findPath("a.b.c.d.e"));

【讨论】:

    【解决方案2】:

    var obj = {
      a: {
        b: {
          c: 1
        }
      }
    }
    
    obj.findPath = function(path) {
      const keys = path.split('.');
      return keys.reduce((currentPath, key) => {
        return currentPath && currentPath[key]
      }, this) 
    }
    
    console.log(obj.findPath('a'))
    console.log(obj.findPath('a.b'))
    console.log(obj.findPath('a.b.c'))
    console.log(obj.findPath('a.b.c.d'))

    【讨论】:

      【解决方案3】:

      这个可以的

      var obj = {
        a: {
          b: {
            c: 1
          }
        }
      }
      function findPath(path) {
        const paths = path.split('.');
        let innerObj = {...obj};
        for (let i = 0; i < paths.length; i++) {
          innerObj = innerObj && innerObj[paths[i]] || null;
        }
        return innerObj;
      }
      
      console.log(findPath("a.b.c"));
      console.log(findPath("a.b"));
      console.log(findPath("a.b.d"));
      console.log(findPath("a.c"));
      console.log(findPath("a.b.c.d"));
      console.log(findPath("a.b.c.d.e"));

      【讨论】:

      • 我给你做了一个sn-p。请在发布时测试您的代码
      • 为什么要将对象存储在新对象中?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-16
      • 2021-12-05
      • 1970-01-01
      • 2020-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多