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


当前回答

添加到String原型是理想的(只是以防它被添加到核心JS语言中),但你首先需要检查它是否存在,如果不存在就添加它,如下所示:

String.prototype.reverse = String.prototype.reverse || function () {
    return this.split('').reverse().join('');
};

其他回答

整个“将字符串反向”是一个过时的C程序员面试问题,被他们面试的人(可能是为了报复?)会问。不幸的是,它的“到位”部分不再起作用,因为几乎所有托管语言(JS, c#等)中的字符串都使用不可变字符串,因此无法在不分配任何新内存的情况下移动字符串。

虽然上面的解决方案确实反转了字符串,但它们在不分配更多内存的情况下不会这样做,因此不满足条件。您需要直接访问分配的字符串,并能够操作其原始内存位置,以便将其反向。

就我个人而言,我真的很讨厌这类面试问题,但遗憾的是,我相信在未来几年里我们还会继续看到它们。

下面的内容可能会帮助任何希望递归反转字符串的人。在最近的一次面试中,我被要求使用函数式编程风格:

var reverseStr = function(str) {
    return (str.length > 0) ? str[str.length - 1] + reverseStr(str.substr(0, str.length -   1)) : '';
};

//tests
console.log(reverseStr('setab retsam')); //master bates

只要你处理的是简单的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
var reverseString = function(str){ 
  let length = str.length - 1;
  str = str.split('');

  for(let i=0;i<= length;i++){
    str[length + i + 1] = str[length - i];
  }

  return str.splice(length + 1).join('');
}