递归函数似乎不会返回值

时间:2017-01-06 15:43:49

标签: javascript arrays recursion

我有一个递归函数,我想从一个对象数组中返回一个对象。数组中的每个对象都包含对"邻居"的引用。对象,像这样:

{
  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 } ]

2 个答案:

答案 0 :(得分:3)

你因此而未定义:

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

此时递归函数不返回任何内容。 当你在你的基础情况下你返回id但它只返回到递归语句。您需要在递归情况下添加一个返回值,以便递归情况也返回答案:

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

答案 1 :(得分:1)

第7行返回该功能。它将按预期工作