Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Apr 2014
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    How do I get a for loop to stop in a particular place?

    Hi!

    I'm trying to get the for loop to stop inspecting every letter once it becomes false.
    This is the code:

    for(var i = 0; i <userName.length; i++){
    if(i !== "a"||"e"||"i"||"o"||"u"){
    spanishName.push(userName[i]);
    }

    "userName" is a string that changes every time (it's put in by the user differently every time the whole program is run).
    I'd like to get the for loop to stop on the exact letter in the string in which it's no longer true, so a different piece of code will run:

    for(var j = i; j <userName.length; j++){
    if(j !== "b"||"c"||"d"||"f"||"g"||"h"||"j"||"k"||"l"||"m"||"n"||"p"||"q"||"r"||"s"||"t"||"v"||"w"||"x"||" z"){
    spanishName.push(userName[j]);
    }
    }

    And then I want that loop to stop in the place when it becomes false so another piece of code can run etc, etc.

    Thanks very much for your help!

  • #2
    New to the CF scene
    Join Date
    Apr 2014
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Sorry! I forgot to mention, what I mean by "no longer true" is not filling the criteria of the if statement underneath.

  • #3
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,918
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    if(i !== "a"||"e"||"i"||"o"||"u"){

    How can i (your loop counter) be anything other than a number?

    Look at the break statement.


    I do not really understand what you are trying to do, but your Javascript syntax is not correct. Apart from anything else, you have confused && (and) with || (or). A statement such as if a !=5 || a != 7 makes no sense.

    Code:
    <script type = "text/javascript">
    
    var userName = "Philip M";
    var spanishName = [];
    var unsplit = userName.split("");
    for (var i = 0; i <unsplit.length; i++) {
    if (unsplit[i] != "a" && unsplit[i] !="e" && unsplit[i] !="i" && unsplit[i] != "o" && unsplit[i] != "u" ) {
    spanishName.push(unsplit[i]); 
    }
    }
    alert (spanishName);
    
    </script>

    But you can strip the vowels from the user name simply by using a regular expression.
    Last edited by Philip M; 04-14-2014 at 02:08 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •