系列章節前端手寫題

[Medium] 請實現 Lodash 的 .get()

2024年1月26日

重點摘要

本文介紹如何實作一個 get 效用函式,此函式可以從一個物件中獲取指定路徑的值。本文也說明了如何處理物件為 null、路徑不存在等情況。

題目描述

實作一個 get  效用函式。它接收三個參數

  • 一個物件
  • 某個路徑
  • 預設值

而此函式最後會返回路徑的值;如果該路徑不存在於給定的物件,則返回預設值。透過例子會比較好理解:

// 範例
const object = { a: [{ b: { c: 3 } }] };

//=> 3
get(object, "a[0].b.c");

//=> 3
get(object, 'a[0]["b"]["c"]');

//=> 'default'
get(object, "a[100].b.c", "default");

本題解答

以下是本題的解答,詳細解題思路可以在 E+ 會員方案 看到。如果想練習更多題目,推薦可以到 GreatFrontEnd 上練習。

function get(object, pathParam, defaultValue) {
  if (object == null) {
    return defaultValue;
  }

  let count = 0;

  const path = Array.isArray(pathParam) ? pathParam : pathParam.split(".");
  const length = path.length;

  while (object != null && count < length) {
    object = object[String(path[count])];
    count += 1;
  }

  const result = count && count === length ? object : undefined;

  return result === undefined ? defaultValue : result;
}
E+ 會員方案

獲得更完整深入的專屬內容

如果你喜歡 ExplainThis 分享的內容,歡迎加入 E+ 會員

除了專屬的文章、影片、社群,也支持 ExplainThis 持續創作