手写lodash/get方法

function isDef(target) {
  return target !== undefined && target !== null;
}

function nextSplit(key) {
  const cartfulIndexs = [];
  const regx = /\[(\d+)\]/g;
  let wholeKey = key;
  let matchResult;
  while ((matchResult = regx.exec(key))) {
    cartfulIndexs.push(matchResult[1]);
  }
  if (cartfulIndexs.length) {
    wholeKey = wholeKey.substring(0, wholeKey.indexOf(cartfulIndexs[0]) - 1);
  }
  return [wholeKey, ...cartfulIndexs];
}

export function get(target, keyStrs, defaultValue) {
  if (!isDef(target)) return defaultValue;

  const keyParts = keyStrs
    .split(".")
    .map(nextSplit)
    .flat();

  let value = target;

  for (let index = 0; index < keyParts.length; index++) {
    const key = keyParts[index];
    console.log(key, value);
    if (isDef(value[key])) {
      value = value[key];
    } else {
      return defaultValue;
    }
  }
  return value;
}


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。