Reverse String in JavaScript

2020-04-16 17:43发布

I wrote a JS constructor which reverse a string variable:

function ReverseString(string) {
    this.str = string;
    var size = this.str.length;
    this.reverse = function () {
        for(size; size >= 0; --size) {
            console.log(this.str[size]);
        }
    }
}

When I invoke a reverse method on a new string object("asd") it produces the following output:

  undefined 
    d 
    s 
    a

Where this undefined came from? Could you help me eliminate this ?

标签: javascript
8条回答
贪生不怕死
2楼-- · 2020-04-16 18:10

What about this easy step

'hello world'.split(' ').map(word=>word.split('').join('')).join(' ');

it will reverse every word in its place

"olleh dlrow"
查看更多
Animai°情兽
3楼-- · 2020-04-16 18:10

Here are three ways to reverse a string in javascript

Iterate through string in reverse order and push letters to array, then join the array

function reverse1(str) {
  if(!str || str.length < 2 || typeof str !== "string") {
    return new Error("Not a valid input");
  }
  const backwards = [];
  for (let i = str.length; i > -1; i--) {
    backwards.push(str[i]);
  }
  return backwards.join('');
}

Use split, reverse, and join methods

function reverse2(str) {
  return str.split().reverse().join();
}

Use ES6 arroe function and spread operator to copy as well as convert the string to array and then reverse and join

reverse3 = str => [...str].reverse().join('');

Call the three functions

console.log(reverse1("Hello World!"));
console.log(reverse2("Hello World!"));
console.log(reverse3("Hello World!"));

Output

!dlroW olleH
Hello World!
!dlroW olleH
查看更多
我想做一个坏孩纸
4楼-- · 2020-04-16 18:12

size at beginning should be length -1. You mix string reversing with string printing, but you can separate it as follows

let str = "Hello World!";
let r = [...str].reverse().join``;
console.log(r);

查看更多
够拽才男人
5楼-- · 2020-04-16 18:14

User recusrsivity, easiest way to do it

function reverse(str){
     if (str.length == 0){ 
        return '';
     }
     return reverse(str.slice(1)) + charAt(0);
}
查看更多
淡お忘
6楼-- · 2020-04-16 18:29

The length problem is already explained. To solve it you could use:

function ReverseString(string) {
    this.str = string;
    var size = this.str.length;
    this.reverse = function () {
        while(size--) {
            console.log(this.str[size]);
        }
    }
}

Another (more simple way) to reverse a string is to split it into an array, reverse that, and join again:

somestring.split('').reverse().join('');

Applied to your method, something like this snippet:

var result = document.querySelector('#result');

function ReverseString(string) {
  this.str = string;
  this.reverse = function() {
    var rev = this.str.split('').reverse();
    void(rev.map(function(v) {
     result.innerHTML += v + '<br>';
    }));
    this.reversed = rev.join('');
  };
}

var myReversed = new ReverseString('hello world');
myReversed.reverse();
<div id="result"></div>

查看更多
做自己的国王
7楼-- · 2020-04-16 18:33

At the beginning, size is going to be 3 (the length). There is nothing at index 3, hence undefined. You need to initiate it at length-1.

var size = this.str.length - 1;
查看更多
登录 后发表回答