Home > Net >  javascript undefine keyword prefix with a string
javascript undefine keyword prefix with a string

Time:06-28

i try to reverse a string by finding the lenght first, using for-loop and den loops throught the range from the lenght to zero and concat it with other variable in order to store it in a reverse order, but i always get undefined prefix to it.

code -

function reverse1(str) {
  let len = 0;
  for (let i in str) {
    len  = 1;
  }
  var r = "";
  for (var i = len; i >= 0; i--) {
    r  = str[i];
  }
  return r;
}
console.log(reverse1("hello"));

output- undefinedolleh

How to get rid of this undefined keyword which get prefix in the reverse string

CodePudding user response:

You Are assigning i in for loop with string length , it should be start from len-1

for (var i = len-1; i >= 0; i--)

CodePudding user response:

  • Maybe there is an easier way to do this, if that what are you going for.
const str = 'Hello World';
const reversed = str .split('').reverse().join('')
console.log(reversed); // dlroW olleH
  • Related