0

I'm trying to do a reverse-word script in javascript. I have written this function, but it does not work and I can't understand why. What is wrong? Is there any other way to do it?

function inverser(x)
{
 var newString ="";
 var index=(x.length - 1);
 var y=0;
 
 for (var i=index ; i>=0 ; i--)
 {
  x[i] = newString [y++];
 }
 
 return (newString );
}
PNB
  • 75
  • 8
  • 2
    Possible duplicate of [How do you reverse a string in place in JavaScript?](http://stackoverflow.com/questions/958908/how-do-you-reverse-a-string-in-place-in-javascript) – Alex May 07 '17 at 16:02
  • logic is totally backwards – charlietfl May 07 '17 at 16:02
  • Your assignment is in reverse. And strings are immutable, you cannot assign to their indices at all. Use an array instead, or build the string through concatenation. – Bergi May 07 '17 at 16:02
  • 1
    "but it does not work" isn't a very helpful description of your problem. What *is* the output for a given input? And what have you done to debug it? – Carcigenicate May 07 '17 at 16:02
  • It should be: `newString [y++] = x[i];` not `x[i] = newString [y++];` – Karim Harazin May 07 '17 at 16:02

3 Answers3

1

You need to add to concatenate newString instead of trying to assign an index to it. The logic of your function should be

newString[y++] += x[i];

Link to code

Garrett Kadillak
  • 952
  • 8
  • 18
0

Use reverse():

function inverser(x)
{   
    return x.split("").reverse().join("");
}

It's simple if you don't need build in function, please comment, i will update my answer :)

Update

The assignment statements are wrong in your code, it should have been:

newString += x[i];
Abishek V Ashok
  • 483
  • 3
  • 17
0

when you use newString[y++], newString is still empty string and doesn't have cell 1 or 2 or 3 .... and can't assign string to this cell.

simply if you remove y variable and make some move on line 9 can get answer.

here the code worked for me:

function inverser(x) {
  var newString = "";
  var index = (x.length - 1);

  for (var i = index; i >= 0; i--)
  {
    newString += x[i];
  }

  return (newString);
}
farbod
  • 91
  • 7