递归函数似乎没有返回值

冰柱

我有一个递归函数,我想从对象数组中返回一个对象。数组中的每个对象都包含对“邻居”对象的引用,如下所示:

{
  id: 5,
  neighbors: {
    north: 1,
    east: 6,
    south: 9,
    west: 4
  }
}

对于那些玩游戏的人,这是4x4板上的5个正方形。

该函数采用所有木板正方形的数组,当前正方形的id和方向:

function findFarthestEmpty(board, id, direction) {
  let nextSquare = board[id].neighbors[direction]
  if (nextSquare === null) {
    console.log('return last square on board', board[id])
    return board[id]
  } else {
    findFarthestEmpty(board, nextSquare, direction)
  }
}
//Try a move.
console.log(typeof(findFarthestEmpty(board, 5, 'north')))

当我如上所述运行函数时,我从第4行获得了正确的方形对象日志记录,但是我的陈述是“未定义的”。也许我混淆了语句和表达式?

如果您需要板阵列:

let board = [ { id: 0,
neighbors: { north: null, east: 1, south: 4, west: null },
meeple: null },
{ id: 1,
neighbors: { north: null, east: 2, south: 5, west: 0 },
meeple: null },
{ id: 2,
neighbors: { north: null, east: 3, south: 6, west: 1 },
meeple: null },
{ id: 3,
neighbors: { north: null, east: null, south: 7, west: 2 },
meeple: null },
{ id: 4,
neighbors: { north: 0, east: 5, south: 8, west: null },
meeple: null },
{ id: 5,
neighbors: { north: 1, east: 6, south: 9, west: 4 },
meeple: null },
{ id: 6,
neighbors: { north: 2, east: 7, south: 10, west: 5 },
meeple: null },
{ id: 7,
neighbors: { north: 3, east: null, south: 11, west: 6 },
meeple: null },
{ id: 8,
neighbors: { north: 4, east: 9, south: 12, west: null },
meeple: null },
{ id: 9,
neighbors: { north: 5, east: 10, south: 13, west: 8 },
meeple: null },
{ id: 10,
neighbors: { north: 6, east: 11, south: 14, west: 9 },
meeple: null },
{ id: 11,
neighbors: { north: 7, east: null, south: 15, west: 10 },
meeple: null },
{ id: 12,
neighbors: { north: 8, east: 13, south: null, west: null },
meeple: null },
{ id: 13,
neighbors: { north: 9, east: 14, south: null, west: 12 },
meeple: null },
{ id: 14,
neighbors: { north: 10, east: 15, south: null, west: 13 },
meeple: null },
{ id: 15,
neighbors: { north: 11, east: null, south: null, west: 14 },
meeple: null } ]
拉桑

由于这个原因,您变得不确定:

typeof(findFarthestEmpty(board, 5, 'north'))

递归函数目前不返回任何内容。在基本情况下,您将返回id,但它仅返回到递归语句。您需要在递归案例中添加一个返回值,以便递归案例也可以返回答案:

else {
   return findFarthestEmpty(board, nextSquare, direction)
  }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章