0

Here's my code's jsfiddle. t

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)))

Here, test(0) should be

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

while you can see it is different in the code's result. How and Why? What do I do to make it right?

4
  • 1
    Clarify your question please. Commented Jun 25, 2012 at 11:29
  • This is not what die Fiddle shows! Commented Jun 25, 2012 at 11:29
  • You might consider using console.log() in the future instead of alert(). Not an answer though. Commented Jun 25, 2012 at 11:30
  • @Furqan oops!! sorry, forgot to update the fiddle and the link. Commented Jun 25, 2012 at 11:30

1 Answer 1

4

You are using a global variable in your recursive function, so it will be changed while you are using it.

Change this:

a = []

to:

var a = []
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.