javascript递归函数错误答案

时间:2012-06-25 11:26:02

标签: javascript recursion

这是my code's jsfiddle。吨

function test(i)
{
  if(i==2)
      return {title:"finished at 2", data:"empty"}
  else
  {
          a=[]
          a.push(test(i+1))
          a.push(test(i+1))
          return {title:"number "+i, data:a}
    }
}

alert(JSON.stringify(test(0)))

此处test(0)应为

{
    title: "number 0",
    data: [{
        title: "number 1",
        data: [{
            title: "finished at 2",
            data: "Empty"
        }, {
            title: "finished at 2",
            data: "Empty"
        }]
    }, {
        title: "number 1",
        data: [{
            title: "finished at 2",
            data: "Empty"
        }, {
            title: "finished at 2",
            data: "Empty"
        }]
    }]

虽然您可以看到它在代码的结果中有所不同。怎么样,为什么?我该怎么做才能做到对不对?

1 个答案:

答案 0 :(得分:4)

您在递归函数中使用全局变量,因此在使用它时会更改它。

改变这个:

a = []

为:

var a = []