简体   繁体   English

function被自己调用多次,如何返回值?

[英]How to return value from function which is called multiple times by itself?

There is some nested object data and I have to go through this several level deep until I find my result.有一些嵌套的 object 数据,我必须深入到 go 直到找到我的结果。 So I use the findByKey function, which is calling itself as often as it is needed.所以我使用findByKey function,它会根据需要经常调用自己。 Then it should return object.source , but I get undefined instead.然后它应该返回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)
      }
    }       
  }
}

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.您递归地运行它,但您没有向上传播返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM