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


当前回答

在ES6中,你还有一个选择

function reverseString (str) {
  return [...str].reverse().join('')
}

reverseString('Hello');

其他回答

字符串本身是不可变的,但是你可以用下面的代码轻松地创建一个反向副本:

function reverseString(str) {

  var strArray = str.split("");
  strArray.reverse();

  var strReverse = strArray.join("");

  return strReverse;
}

reverseString("hello");

只要你处理的是简单的ASCII字符,并且你很乐意使用内置函数,这就可以工作:

function reverse(s){
    return s.split("").reverse().join("");
}

如果您需要一个支持UTF-16或其他多字节字符的解决方案,请注意这个函数会给出无效的unicode字符串,或者看起来很滑稽的有效字符串。你可以考虑一下这个答案。

[…s]是Unicode感知的,一个小的编辑给出:-

function reverse(s){
    return [...s].reverse().join("");
}

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

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('apple') === 'leppa'
//reverse('hello') === 'olleh'
//reverse('Greetings!') === '!sgniteerG'

// 1. First method without using reverse function and negative for loop
function reverseFirst(str) {
    if(str !== '' || str !==undefined || str !== null) {
        const reversedStr = [];
        for(var i=str.length; i>-1; i--) {
        reversedStr.push(str[i]);
        }
    return reversedStr.join("").toString();
    }
}

// 2. Second method using the reverse function
function reverseSecond(str) {
    return str.split('').reverse().join('');
}

// 3. Third method using the positive for loop
function reverseThird(str){
    const reversedStr = [];
    for(i=0; i<str.length;i++) {
        reversedStr.push(str[str.length-1-i])
    }
    return reversedStr.join('').toString();
}

// 4. using the modified for loop ES6
function reverseForth(str) {
    const reversedStr = [];
    for(let character of str) {
        reversedStr = character + reversedStr;
    }
    return reversedStr;
}

// 5. Using Reduce function
function reverse(str) {
    return str.split('').reduce((reversed, character) => {
        return character + reversed;  
    }, '');
}