简体   繁体   中英

Why is this code performing an infinite loop?

  <script>
  $(document).ready(function(){
  var names = ['Hannah', 'Lucy', 'Brenda', 'Lauren', 'Mary'];
  var liked = [];
  var disliked = [];

         while(names.length > 0){

          document.getElementById('demo').innerHTML =  names[i];
          function likeOrDislike(choice){
          if(choice == 'Like')
          {
            liked.push(names[0])
            names.splice(0, 1)
          }
          else if (choice == 'Dislike')
          {
            disliked.push(names[i])
            names.splice(0, 1)
          }

        };
   };
 });
  </script>

I am asking the while loop to continue until the arrays names is empty. I am then getting the user replacing the text each time with the first name in the array. I am then either choosing like/dislike and then removing the first name of the array and repeating the process until the names array is empty.

However, when I load in the browser it does not load up the page as I think it is stuck in a loop

Besides an undefined i as pointed out in the comments, you're never changing names

All of your processing against names is done within the function function likeOrDislike() and you never call it.

So this is happening:

  • while there are names ( names >0 ) then do the contents of this stub
  • ... and that's it. you never change names.
  • ... the function is never called.

Perhaps you're meaning to do something like this - this is just an example, totally assuming what you're trying to acheive.

$(document).ready(function(){
  var names = ['Hannah', 'Lucy', 'Brenda', 'Lauren', 'Mary'];
  var liked = [];
  var disliked = [];

  $('#yourLikeButton').click(function(){
    var name = $(this).data('name'); // on your button put data-name="Hannah"
    var idx = names.indexOf(name);
    liked.push(names[idx]); // this is if you're playing around with indexes
    names.splice(idx, 1); // this is if you're playing around with indexes
  });

  // similar for your dislike button      

 });

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