简体   繁体   中英

Javascript recursion loop items to array

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)

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM