简体   繁体   中英

Infinite Loop error in my assignment; don't know how to fix

My task is to create a function using while loops that converts all e's in a sentence to a 3, and all a's to a 4. 'Hacker Speak'. My function right now puts the browser into an infinite loop. I don't know what I'm doing wrong.

 function hackerSpeak() { var sentence2 = document.getElementById('sentence2').value; var milk = false; var counting = 0; while (!milk) { if (counting == sentence2.value) { milk = true; } else if (sentence2.charCodeAt(counting) == "e") { sentence2.replace(counting, "3") counting++; } else if (sentence2.charCodeAt(counting) == "a") { sentence2.replace(counting, "4") counting++; } else { counting++; } } document.getElementById('replaceThree').innerHTML = sentence2; }
 Function 3: Hack speak<br> <textarea id="sentence2" class="try"></textarea><br> <button onclick="hackerSpeak()">Convert!</button> <div id="replaceThree"></div>

You are making it too complex. The replace method in JavaScript does not take an index as a parameter, but has the following parameters: string.replace(searchvalue, newvalue) .

And there is no need to use a loop to do what you are after.

You are trying to use replace by passing the index of a character in a string which is not supported by replace method.

Simple solution without using a loop

Instead, to meet your requirements, you should use following script.

 Function 3: Hack speak<br>
    <textarea id="sentence2" class="try"></textarea><br>
    <button onclick="hackerSpeak()">Convert!</button>
    <div id="replaceThree"></div>


 <script>
 function hackerSpeak(){
  var sentence2 = document.getElementById('sentence2').value;
  document.getElementById('replaceThree').innerHTML = sentence2.replace("a","4").replace("e","3");
 }
 </script>

Another solution using a while loop

If you still had to use a loop then modify your code to what is given below. A demo can be seen at running demo

Note that with a loop approach you have to re-construct a sentence character by character starting from the first character in original sentence. The variable newSentence will be constructed one character at a time using the business rules you have. This approach uses string concatenation when adding each character to newSentence value.

Function 3: Hack speak<br>
    <textarea id="sentence2" class="try"></textarea><br>
    <button onclick="hackerSpeak()">Convert!</button>
    <div id="replaceThree"></div>



 <script>
 function hackerSpeak(){
  var sentence2 = document.getElementById('sentence2').value.trim();
  var milk = false;
  var counting = 0;
  var newSentence = "";
  while(milk === false){
  if(sentence2.length == 0 || counting > (sentence2.length -1)){
     milk = true;
  }
  else if(sentence2.charAt(counting)==="e"){
     newSentence =  newSentence + "3";// sentence2.replace(counting, "3")
     counting++;
  }
  else if(sentence2.charAt(counting)==="a"){
     newSentence =  newSentence + "4";//sentence2.replace(counting, "4")
     counting++;
  }
  else{
    newSentence = newSentence + sentence2.charAt(counting);
    counting++;
   }
  }//end of while loop
  document.getElementById('replaceThree').innerHTML = newSentence;
}
</script>

The only problem which i could see is exiting the while loop. Instead of using sentence2.value you can compare it with sentence.length

try the below code for exiting

if(counting==sentence2.length){
     milk = true;
  }

even in the replace function, it not works with the indexing, you can use

if (sentence2.charCodeAt(counting) == "e") {
      sentence2.replace("e", "3")
      counting++;
    } else if (sentence2.charCodeAt(counting) == "a") {
      sentence2.replace("a", "4")
      counting++;
    } else {
      counting++;
    }

once the counter is updated, it will match for the length of sentence2 and exit the loop.

The code will become increasingly large and clumsy as new substitutions appear.

// array of characters to replace and their replacments - 
// easier to extend the array to include new values without 
// forcing code become more aware 
var hackerSwaps = [
    ['a', 'e', 'o'],    // n00bspeak
    ['4', '3', '0']     // 1337sp34k
];

// args to function are id properties of sentence and output target
 function hackerSpeak(sId, outId) {
    // convenience reference 
    function get(eId) {return document.getElementById(eId);};

    // split sentence into character array
    var s = get(sId).value.split('');
    // for each pair of items in the character swapping array
    for (var j = 0; j < hackerSwaps[0].length; j++) {
        var c = hackerSwaps[0][j];  // get n00b char
        var h = hackerSwaps[1][j];  // get 1337 replacement
        // for each character in sentence
        for (var i = 0; i < s.length; i++) {
            if (s[i] == c) s[i] = h;
        }
    }
      // convert back to String and write to page
      get(outId).innerHTML = s.join('');
};

And for the HTML...

    <form>
            <textarea id="sentence2" class="try">some content with 'a' and 'e' characters</textarea><br>
            <input type="button" onclick="hackerSpeak('sentence2', 'replaceThree');" value="Convert!" />
            <div id="replaceThree">nothing</div>
    </form>
    <p id="replaceThree"></p>

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