美文网首页
2021-03-16 实现lodash 的 .get

2021-03-16 实现lodash 的 .get

作者: 威少带我砍三双 | 来源:发表于2021-03-16 13:02 被阅读0次

在js中经常会出现嵌套调用这种情况,如ab.cde,但是这么写很容易抛出异常。

你需要这么写a&&ab&&abc&&abcd&&ab.cd.e,但是显得有些啰嗦与冗长了。

特别是在 graph中,这种嵌套调用更是难以避兔。

这时就需要一个get函数,使用geta,"b.cd.e")简单清晰,并且容错性提高了很多。

1)代码实现

function get(source, path, defaultValue = undefined) {
  // a[3].b -> a.3.b -> [a,3,b]
 // path 中也可能是数组的路径,全部转化成 . 运算符并组成数组
  const paths = path.replace(/\[(\d+)\]/g, ".$1").split(".");
  let result = source;
  for (const p of paths) {
    // 注意 null 与 undefined 取属性会报错,所以使用 Object 包装一下。
    result = Object(result)[p];
    if (result == undefined) {
      return defaultValue;
    }
  }
  return result;
}
// 测试用例
console.log(get({ a: null }, "a.b.c", 3)); // output: 3
console.log(get({ a: undefined }, "a", 3)); // output: 3
console.log(get({ a: null }, "a", 3)); // output: 3
console.log(get({ a: [{ b: 1 }] }, "a[0].b", 3)); // output: 1

相关文章

网友评论

      本文标题:2021-03-16 实现lodash 的 .get

      本文链接:https://www.haomeiwen.com/subject/eofdcltx.html