首页 > 解决方案 > 如何从自身多次调用的函数中返回值?

问题描述

有一些嵌套的对象数据,我必须深入这几个层次,直到找到我的结果。所以我使用了这个findByKey函数,它会根据需要经常调用自己。然后它应该返回object.source,但我得到undefined了。

async function getData(lib, level) {
  // First get data from file
  const depsBuffer = await readFile(resolve('file.json'))
  const deps = JSON.parse(depsBuffer.toString('utf-8'))

  // Process data
  const result = findByKey(deps.dependencies, deps.dependencies)
  console.log(result) // returns undefined :-(
}

function findByKey(data, deps) {
  if (data.hasOwnProperty('target') && data.target === 'param') {
    return data
  }
  for (let i = 0; i < Object.keys(data).length; i++) {
    const element = data[Object.keys(data)[i]]
    if (typeof element === 'object') {
      let obj = findByKey(element, deps)
      if (obj != null) {
        if (RegExp(/.*/).test(obj.source)) return obj.source // <- Return this to `getData`
        // else if (!obj?.source?.startsWith('npm:')) findByKey(deps, deps)
      }
    }       
  }
}

标签: javascript

解决方案


I belive your issue is that

else if (!obj?.source?.startsWith('npm:')) findByKey(deps, deps)

should be

else if (!obj?.source?.startsWith('npm:')) return findByKey(deps, deps)

You are running it recursively, but you are not propagating the return value upward.


推荐阅读