Reversing a string in JavaScript

后端 未结 15 1977
野的像风
野的像风 2020-11-28 03:58

I\'m trying to reverse an input string

var oneway = document.getElementById(\'input_field\').value();
var backway = oneway.reverse();

but f

15条回答
  •  难免孤独
    2020-11-28 04:46

    This reverse prototype function is implemented using "this". If you see log console of "this", it will generate the array, and it has length property. So that it!!! Just use reverse "for-loop" as shown in the code snippet.

    String.prototype.reverse = function () {
        console.log(this);
        var result = "";
        var len = this.length;
        
        for (i = (len-1); i >= 0 ; i--) {
            result += this[i];
        }
        return result;
    };
    
    alert("elahnu jaknap".reverse());

提交回复
热议问题