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:34

I would use reduceRight:

function sum(arr) {
    return arr.reduceRight(function(result, chr) {
        return result += chr;
    });
}

Now I have a handy routine I can also use to sum up sequences of numbers (in reverse order, but that doesn't matter).. For string:

function reverse_string(str) {
    return sum(str.split(''));
}
查看更多
劳资没心,怎么记你
3楼-- · 2020-04-16 18:36

In here you have get the size of the 'string' constructor parameter and you decrese the length of the given word('size' variable).

function ReverseString(string)     { 
this.str = string; 
var size = this.str.length;
this.reverse = function () {
 for(size; size >= 0; --size)  //loop from index value 3 to 0
{ console.log(this.str[size]);
 } 
}
}

But the problem is when you input word 'asd', the length of that string is 3. So, when you access the index of str[3] should be undefined. Because,

    index[0] --> a
    index[1] --> s
    index[2] --> d
    index[3] --> undfined

So, your code should change,

function ReverseString(string)   { this.str = string; 
var size = this.str.length; 
this.reverse = function () {
 for(size; size > 0; --size) //loop from index value 2 to 0
 { console.log(this.str[size - 1]);
 } 
}
}

So, output should be like this,

    index[0] --> a
    index[1] --> s
    index[2] --> d
查看更多
登录 后发表回答