简体   繁体   中英

How to stop the rest of the code from being executed - javascript

If the condition in the for loop is met, i want the code to stop running. Although, if the condition is not met, i want the code to continue outside the for loop and execute the alert.

Many sources told me to use the 'return' keyword. I have used it, but the alert still runs even when the condition is met.

Have i placed the keyword in the wrong place? or is there a better way to stop the function when the condition is met?

This is my javascript:

 function addEvent() { var snumber = document.getElementById('snumberE').value; var pass = document.getElementById('passE').value; var passS = String(pass) var snumS = String(snumber) var arr = JSON.parse(localStorage.getItem('profiles')); for(var i=0; i<arr.length; i++) { if(arr[i].password == passS && arr[i].snumber == snumS) { window.location = "StudentView.html"; alert('YEAAA'); return; } } alert('Please enter valid login info'); } function addEvt() { var uname = document.getElementById('name').value; var psw = document.getElementById('pass').value; var arr1 = JSON.parse(localStorage.getItem('profilesT')); for(var i=0; i<arr1.length; i++) { var uname = document.getElementById('name').value; var psw = document.getElementById('pass').value; if(arr1[i].pass1 == psw && arr1[i].usern == uname) { window.open('createAnnouncement.html'); return; } } alert('Please enter valid credentials or sign up'); } 

return should do what you want and exit the function where you are calling it.

Can see in this simplified version that the alert won't fire. Your conditionals aren't doing what you expect or the stored data isn't what you expect

 function test() { var nums = [1, 2, 3, 4, 5, 6]; for (var i = 0; i < nums.length; i++) { console.log('Loop fired for number ' + nums[i]); if (nums[i] === 3) { console.log('return now exiting function') return; } } alert("This alert shouldn't fire") } test(); 

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