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


当前回答

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

其他回答

真正的答案是:你不能把它颠倒过来,但是你可以创建一个颠倒过来的新字符串。

Just as an exercise to play with recursion: sometimes when you go to an interview, the interviewer may ask you how to do this using recursion, and I think the "preferred answer" might be "I would rather not do this in recursion as it can easily cause a stack overflow" (because it is O(n) rather than O(log n). If it is O(log n), it is quite difficult to get a stack overflow -- 4 billion items could be handled by a stack level of 32, as 2 ** 32 is 4294967296. But if it is O(n), then it can easily get a stack overflow.

有时候面试官还是会问你,“作为练习,你为什么不用递归来写呢?”就是这样:

String.prototype.reverse = function() {
    if (this.length <= 1) return this;
    else return this.slice(1).reverse() + this.slice(0,1);
}

测试运行:

var s = "";
for(var i = 0; i < 1000; i++) {
    s += ("apple" + i);
}
console.log(s.reverse());

输出:

999elppa899elppa...2elppa1elppa0elppa

为了尝试获得堆栈溢出,我在谷歌Chrome中将1000更改为10000,它报告:

RangeError: Maximum call stack size exceeded

没有将字符串转换为数组;

String.prototype.reverse = function() {

    var ret = "";
    var size = 0;

    for (var i = this.length - 1; -1 < i; i -= size) {

        if (
          '\uD800' <= this[i - 1] && this[i - 1] <= '\uDBFF' && 
          '\uDC00' <= this[i]     && this[i]     <= '\uDFFF'
        ) {
            size = 2;
            ret += this[i - 1] + this[i];
        } else {
            size = 1;
            ret += this[i];
        }
    }

    return ret;
}

console.log('anãnam anañam' === 'mañana mañana'.reverse());

使用数组。反向而不将字符转换为代码点;

String.prototype.reverse = function() {

    var array = this.split("").reverse();

    for (var i = 0; i < this.length; ++i) {

        if (
          '\uD800' <= this[i - 1] && this[i - 1] <= '\uDBFF' && 
          '\uDC00' <= this[i]     && this[i]     <= '\uDFFF'
        ) {
            array[i - 1] = array[i - 1] + array[i];
            array[i] = array[i - 1].substr(0, 1);
            array[i - 1] = array[i - 1].substr(1, 1);
        }

    }

    return array.join("");
}

console.log('anãnam anañam' === 'mañana mañana'.reverse());

使用内置函数反转字符串

函数reverse(str) { //使用split()方法返回一个新数组 //使用reverse()方法反转新创建的数组 //使用join()方法将数组中的所有元素连接成一个字符串 返回str.split (" ") .reverse () . join (" "); } console.log(反向('你好'));


反转一个没有helper的字符串

函数reversedOf(str) { let newStr = "; For (let char of str) { newStr = char + newStr / /轮1:“h”+“= h,第二轮:“e”+“h”=“嗯”…等。 / / console.log (newStr); } 返回newStr; } console.log (reversedOf('你好'));

function reverse_string(string)
{
var string;

var len = string.length;

var stringExp = string.split('');
var i;
for (i = len-1; i >=0;i--)
{
var result = document.write(stringExp[i]);
}

return result;
}

reverse_string("This is a reversed string");

//outputs: gnirts描述一个sihT

下面是一个基本的ES6不可变的例子,没有使用Array.prototype.reverse:

//:: reverse = String ->字符串 const reverse = s => []. reduceright .使用实例调用(s, (a, b) => a + b) Console.log (reverse('foo')) // => 'oof' Console.log (reverse('bar')) // => 'rab' Console.log (reverse('foo-bar')) // => ' rabb -oof'