当一个字符串被传递给一个带有返回语句的函数时,你如何在JavaScript中反转它,而不使用内置函数(.reverse(), . charat()等)?


当前回答

word.split('').reduce((acc, curr) => curr+""+acc)

其他回答

其中一种方法也可以是在使用分割法后再使用还原法进行逆向。

函数reverse(str) { 返回str.split(”)。reduce((rev, currentChar) => currentChar + rev, "); } console.log(反向('苹果')); console.log(反向('你好')); console.log(反向(“问候!”);

使用Array函数,

String.prototype.reverse = function(){
    return [].reduceRight.call(this, function(last, secLast){return last + secLast});
}
String.prototype.reverse_string=function() {return this.split("").reverse().join("");}

or

String.prototype.reverse_string = function() {
    var s = "";
    var i = this.length;
    while (i>0) {
        s += this.substring(i-1,i);
        i--;
    }
    return s;
}

如果你不想使用任何内置功能。试试这个

var string = 'abcdefg';
var newstring = '';

for(let i = 0; i < string.length; i++){
    newstring = string[i] += newstring;
}

console.log(newstring);

在一次面试中,我被要求在不使用任何变量或本机方法的情况下反转一个字符串。这是我最喜欢的实现:

function reverseString(str) {
    return str === '' ? '' : reverseString(str.slice(1)) + str[0];
}