-1

I'm trying to swap every character in this string:

"hiya you guys are awesome!"

The output should come out to be:

"ihayy uog yu sra ewasemo!e"

I've written the following code - unfortunately, it keeps triggering an infinite loop. I've tried several iterations of it but can't figure out why I can't stop the loop? Could someone help explain why this is happening?

Thanks in advance!

var input = 'hiya you guys are awesome!';

function flip (string) {
  var flipped = [] 
  var flippedRejoin = []
  var brokenString = string.split('')
//console.log(brokenString)
  for (var i = 0; i < string.length; i+1) {
    flipped.push(brokenString[i+1]);
    flipped.push(brokenString[i]);
//  console.log(flipped);
  }
//for (var e = 0; e < string.length; e++) {
    flippedRejoin = flipped.join('')
    console.log(flippedRejoin)
//}


  return flippedRejoin
}
flip(input)
AP.
  • 8,082
  • 2
  • 24
  • 33
alexforyou
  • 93
  • 1
  • 4

1 Answers1

1

Your for loop is wrong, do :

for (var i = 0; i < string.length-1; i+=2) {

i+1 will not change i in any way, so you need to increment it by two ( as you wanna flip pairs ) instead. And as youre accessing i+1 it might be better to stop at length-1 ...

All in all:

function flip (string) {
  var flipped = [];
  for (var i = 0; i < string.length-1; i+=2) {
      flipped.push(string[i+1],string[i]);
  }
   return flipped.join('');
 }

http://jsbin.com/tohositide/edit?console

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • ah wow. Thanks for that. Can I ask what the i+=2 is doing rather than just i+2? Why do I need that equal sign there? Also why is the original code creating the infinite loop conceptually? You say that "i+1 will not change i in any way". Why is this any different than i++? – alexforyou May 25 '17 at 15:20
  • @alexforyou i+2 returns a value but it does not change i. i+=2 increases i by two. – Jonas Wilms May 25 '17 at 15:22
  • @alexforyou `i+=2` is the same as `i = i + 2` whereas `i + 1` simply returns `1` every time, since you're not setting it back to `i` – AP. May 25 '17 at 15:27
  • @alexforyou https://stackoverflow.com/questions/6867876/javascript-i-vs-i – evolutionxbox May 25 '17 at 15:44
  • @evolutionxbox not related to the problem – Jonas Wilms May 25 '17 at 15:45
  • @Jonasw _"Why is this any different than i++?"_ I linked a useful question explaining what `i++` does. – evolutionxbox May 25 '17 at 15:47