简体   繁体   中英

I am going through infinite loop when adding values to array

I have created an array with some movie names by default. I have an form which asks for user input, if the user input matches with my default array it should pop up that movie already exists, if user input is different from my default array it should store in different array. I have done the first part but I'm getting issues with adding values to array

 function insert() { var movie = document.getElementById("movie").value; var movie2 = []; for (var i = 0; i <= movie2.length; i++) { if (movie !== movie2[i]) { movie2.push(movie); var name2 = "Movie added into Array2"; alert(name2); } else { var name2 = "Movie already added to Array2"; alert(name2); } } } function validation() { var movie = document.getElementById("movie").value; var movie1 = ["Bahubali", "The Final Destination", "The Cars", "PK", "Bajarangi Baijaan", "Force"]; if (movie == "") { var name2 = "Please enter your favoite movie name"; alert(name2); } for (var i = 0; i < movie1.length; i++) { if (movie == movie1[i]) { var name2 = "Movie exists in our database"; alert(name2); } else { insert(); } } } 
 <html> <head> <title>Movie Mania</title> <link rel="stylesheet" type="text/css" href="Movie.css"> <script src="Movie.js"></script> </head> <body> <div class="content"> <div class="matter"> <p class="header">Movie Mania</p> <div class="regis"> <form class="reg"> <input type="text" name="user" id="movie" placeholder="Please enter any movie name" size="40"> <hr> <div><input type="submit" class="button" value="Search" id="sub" onclick="validation()" /></div> </div> </div> </div> </form> </body> </html> 

It's for loop problem .

Explanation of for loop problem

See the console.log matching the condition for each arguments of array. you are not breaking after the true statement. so only else statement also run( insert ) until for loop finishing

 var one = "hi" var arr = ['hello', 'hi', 'how'] for (var i = 0; i < arr.length; i++) { console.log(arr[i] == one) if (arr[i] == one) { break; } } 

Solution: you should use break statement .

See the console.log the loop was stopped the execution after break

 var one="hi" var arr = ['hello','hi','how'] for(var i=0; i< arr.length; i++){ console.log(arr[i] == one) } 

For better use with Array#includes instead of for loop iteration

Updated:

remove the movie2 .push(movie) with movie1 and declare the movie1 array as a global

 var movie1 = ["Bahubali", "The Final Destination", "The Cars ","PK "," Bajarangi Baijaan ","Force "]; function insert() { var movie = document.getElementById("movie").value; if (!movie1.includes(movie)) { // ! refer for false statement movie1.push(movie); var name2 = "Movie added into Array2"; console.log(name2); } else { var name2 = "Movie already added to Array2"; cosole.log(name2); } console.log(movie1) } function validation() { var movie = document.getElementById("movie").value; if (!movie.trim()) { //its validate the input empty undefined null var name2 = "Please enter your favoite movie name"; console.log(name2); } else if (movie1.includes(movie)) { // includes used for find the value is in array or not var name2 = "Movie exists in our database"; console.log(name2); } else { insert(); } return false; } 
 <div class="content"> <div class="matter"> <p class="header">Movie Mania</p> <div class="regis"> <form class="reg"> <input type="text" name="user" id="movie" placeholder="Please enter any movie name" size="40"> <hr> <div><input type="submit" class="button" value="Search" id="sub" onclick="return validation()" /></div> </div> </div> </div> </form> 

the cause of the infinite loop is:

var movie2 = [];
for (var i = 0; i <= movie2.length; i++) {
    if (movie !== movie2[i]) {
      movie2.push(movie);
      var name2 = "Movie added into Array2";
      alert(name2);
    } else {
      var name2 = "Movie already added to Array2";
      alert(name2);
    }
  }

you start with i = 0 and since the array is empty this will be true i <= movie2.length since the array is empty movie2[i] == undefined so you push the movie to the array, next iteration i will be 1 and movie2.length will be 1 too but movie2[1] is undefined so you push the movie again, and that will keep repeating.

One way to solve this is to check if the movie exist or not then push it:

this code still have some other issues unrelated to the question

 function insert() { var movie = document.getElementById("movie").value; var movie2 = []; var found = false; for (var i = 0; i < movie2.length; i++) { if (movie !== movie2[i]) { found = true break; } } if (!found) { movie2.push(movie); var name2 = "Movie added into Array2"; alert(name2); } else { var name2 = "Movie already added to Array2"; alert(name2); } } function validation() { var movie = document.getElementById("movie").value; var movie1 = ["Bahubali", "The Final Destination", "The Cars", "PK", "Bajarangi Baijaan", "Force"]; if (movie == "") { var name2 = "Please enter your favoite movie name"; alert(name2); } for (var i = 0; i < movie1.length; i++) { if (movie == movie1[i]) { var name2 = "Movie exists in our database"; alert(name2); } else { insert(); } } } 
 <html> <head> <title>Movie Mania</title> <link rel="stylesheet" type="text/css" href="Movie.css"> <script src="Movie.js"></script> </head> <body> <div class="content"> <div class="matter"> <p class="header">Movie Mania</p> <div class="regis"> <form class="reg"> <input type="text" name="user" id="movie" placeholder="Please enter any movie name" size="40"> <hr> <div><input type="submit" class="button" value="Search" id="sub" onclick="validation()" /></div> </div> </div> </div> </form> </body> </html> 

a slightly improved version

 var movie1 = ["Bahubali", "The Final Destination", "The Cars", "PK", "Bajarangi Baijaan", "Force"]; var movie2 = []; function insert() { var movie = document.getElementById("movie").value; var found = false; for (var i = 0; i < movie2.length; i++) { if (movie !== movie2[i]) { found = true break; } } if (!found) { movie2.push(movie); var name2 = "Movie added into Array2"; alert(name2); } else { var name2 = "Movie already added to Array2"; alert(name2); } } function validation() { var movie = document.getElementById("movie").value; if (movie == "") { var name2 = "Please enter your favoite movie name"; alert(name2); } var found = false; for (var i = 0; i < movie1.length; i++) { if (movie == movie1[i]) { found = true break; } } if (found) { var name2 = "Movie exists in our database"; alert(name2); } else { insert(); } } 
 <html> <head> <title>Movie Mania</title> <link rel="stylesheet" type="text/css" href="Movie.css"> <script src="Movie.js"></script> </head> <body> <div class="content"> <div class="matter"> <p class="header">Movie Mania</p> <div class="regis"> <form class="reg"> <input type="text" name="user" id="movie" placeholder="Please enter any movie name" size="40"> <hr> <div><input type="submit" class="button" value="Search" id="sub" onclick="validation()" /></div> </div> </div> </div> </form> </body> </html> 

The problem that you are facing is in your loop logic. You are visiting every element of the array and checking if that element is equal to the new value. If it is not then you are inserting the value.

Say your array contained:

 ["A", "B"]

And you wish to insert "C".

First, you code is comparing "A" to "C" and since they are not equal you are inserting "C" so the array becomes

["A", "B", "C"]

Then your for loop moves on to compare "B" and "C" and since they are not equal you are inserting "C" again.

To make matters worse your insert method is also doing a similar task by looping through the array again and actually inserting the new value for every movie that is already in your array.

So to solve the problem your logic should be:

  1. Check if the movie exist in the array
  2. If not insert it
  3. If it does provide a message.

To check if the movie already exist in the array you may use the includes method of arrays. Something like this:

   if (movie1.includes(movie)){
      //movie is already in array
   }else{
      //movie is not yet in array
   }

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