递归函数返回空arrray

时间:2018-03-09 02:45:06

标签: javascript

我遇到了递归函数getPath的问题,因为它返回一个空数组,它应该返回一个如下所示的数组:

['main', 'children', 'name']

我不确定逻辑削减是否正确,因为这不是问题所在,问题是,为什么我的数组是空的?它将数据推送到数组,但最终结果是一个空数组。

let dataScope = [{
  "name": "main",
  "location": [":data"]
}, {
  "name": "child",
  "location": ["main", "children"]
}]

function getLocation(key) {
  let val = dataScope.find(i => i.name == key)
  return val ? val.location : []
}

function getPath(items) {
  let path = []
  let item = items.shift()
  if (item) {
    let loc = getLocation(item)
    if (loc.length > 0 && loc.join('.') != ':data') {
      path.push(...getPath(loc))
      console.log('added to array')
    }
  }
  return path
}

console.log(getPath(['child', 'name']))

3 个答案:

答案 0 :(得分:1)

你不能对loc做任何事情,所以似乎什么都没有被推到阵列

注意:我仍然试图掌握原始代码导致空数组的原因 - 但是,此代码会产生预期结果:p



let dataScope = [{
  "name": "main",
  "location": [":data"]
}, {
  "name": "child",
  "location": ["main", "children"]
}]

function getLocation(key) {
  let val = dataScope.find(i => i.name == key);
  return val ? val.location : []
}

function getPath(items, indent = 0) {
  let z = items.join(',');
  console.log(`${' '.repeat(indent)}called with ${z}`);
  let path = [];
  let item = items.shift();
  let loc = [];
  if (item) {
    loc = getLocation(item);
    if (loc.length > 0 && loc.join('.') != ':data') {
      path.push(...getPath(loc.slice(), indent + 4)); // .slice() so loc isn't mutated
      console.log(`${' '.repeat(indent)}${z} has path [${path.join(',')}]`);
    }
    path.push(...loc); // add loc to the path - comment this out to see the difference
  }
  console.log(`${' '.repeat(indent)}${z} returns [${path.join(',')}]`);
  return path
}

console.log(`[${getPath(['child', 'name'])}]`)




答案 1 :(得分:0)

首先,您将一组名称传递给getPath,但稍后您将传递位置数组。应该是哪一个?逻辑需要调整。并且数据集中没有使用值" name"所以你的测试也是不正确的。

答案 2 :(得分:0)

这是因为您正在进行递送发送dataScope location,但是您实现了getPath期待dataScope keys

let dataScope = [{
  "name": "main",
  "location": [":data"]
}, {
  "name": "child",
  "location": ["main", "children"]
}]

function getLocation(key) {
  let val = dataScope.find(i => i.name == key)
  return val ? val.location : []
}

function getPath(keys) { // changing items name to keys for clarification
  let path = []
  let key = keys.shift()
  if (key) {
    let loc = getLocation(key);
    if (loc.length > 0 && loc.join('.') != ':data') {
      path.push(...loc) // push locs into array
      getPath(keys) // call getPath with remaining keys
      console.log('added to array')
    }
  }
  return path
}

console.log(getPath(['child', 'main']))

由于此声明,您:data结果不会pathloc.join('.') != ':data'。如果你删除它,你将获得预期的输出。