Javascript recursion loop items to array

19,200

Solution 1

You're creating a new array instead of passing it to the recursive call.

Do this instead.

DEMO: http://jsfiddle.net/kDtZn/

function addToArray(array) {
    array.push(prompt("Add items to array or 'q' to stop"));
    if (array[array.length-1] == 'q') {
        array.pop();
        document.write(array)
    }
    else {
        addToArray(array);
    }
 }
 addToArray([]);

Now you start with an empty array, and for each recursive call, it passes the same array forward.

Also, I changed it so that it doesn't use .pop() in the if() condition, otherwise you'll always end up with an empty array when it comes time to write it. (The .pop() method actually removes the last item.)

Finally, make sure you're not using document.write after the DOM is loaded. If so, you need to change it to use DOM manipulation methods instead.


You could take a different approach so that you don't need .pop() at all.

DEMO: http://jsfiddle.net/kDtZn/1/

function addToArray(array) {
    var item = prompt("Add items to array or 'q' to stop");
    if (item == 'q') {
        document.body.textContent = array;
    } else {
        array.push(item);
        addToArray(array);
    }
}
addToArray([]);

The reason your while loop didn't work is very likely because of the original .pop() issue.

Solution 2

Your function recreates var array = [] on every loop/recursion. I am not sure if recursion is the right tool for the job in your case - it does not seems like it - but if you're starting out with JavaScript/development and just trying it out then you're fine.

Solution 3

While an 'infinite loop' is probably what you really want (as it would probably make the code simpler), you can do this with recursion by defaulting the array and passing it as an argument to the function. Like so...

function addToArray( array ) {
  var array = array || [];
  array.push(prompt( "Add items to array or 'q' to stop" ));
  if ( array[array.length - 1] === 'q' ) {
    document.write(array.slice( 0, -1 ))
  } else {
    addToArray( array );
  }
}

addToArray();

There's two issues with the code as you presented. One, as pointed out earlier, you're redefining your array variable every time you call your function. Second, array.pop() alters your array, so when you get to the document.write call, you'd be printing an empty array anyways.

Share:
19,200

Related videos on Youtube

Jerry Walker
Author by

Jerry Walker

Updated on September 20, 2022

Comments

  • Jerry Walker
    Jerry Walker over 1 year

    I am trying to make a small program that prompts a user to add items to a grocery list.

    I read about using recursion to loop. I understand a while loop would probably be better suited for this task, but I ran into the same problems with the while loop and I wanted to try recursion. It just sounds like I know what I'm doing... "Yeh, I used recursion to enumerate the array while prompting validation from the user... hur hur hur"... but, I digress.

    Here is the code:

    function addToArray() {
              var array = [];
              array.push(prompt("Add items to array or 'q' to stop"));
              if (array.pop() == 'q') {
                  document.write(array)
              }
              else {
                  addToArray();
              }
          }
          addToArray();
    

    If you'll notice, it loops like its supposed to but it is not adding items to an array. I have tried the array[i] = i technique as well but to no avail, the array remains empty. Also, why is it that by using a function with no args am I not running into too much recursion? Is it because of the conditional statement?

    If you know what I'm doing wrong, try and hint towards the right answer rather than just blurting it out. I'd like to have that 'Aha' moment. I think this all helps us learn a bit better.

    Thanks guys. (and gals)

    • zerkms
      zerkms over 10 years
      hint #1: var array = []; creates a new array on every function call
    • zerkms
      zerkms over 10 years
      hint #2: you don't need a recursion but an infinite loop
  • Jerry Walker
    Jerry Walker over 10 years
    Hey thanks man. It was the pop() that was causing the issue. I realized it displayed the last item in the array, but forgot that it deletes it as well. Could you explain what, in essence, the array[array.length-1] == 'q' is doing? What would array.length-1 represent?
  • Jerry Walker
    Jerry Walker over 10 years
    Nvm figured it out. It is referencing the last item of the array. 0 being array item 1, and -1 representing the last item. Thanks man.