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


当前回答

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

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

其他回答

函数反向(字符串) { Let arr = []; For (let char of string) { arr.unshift (char); } Let rev = arr.join(") 返回牧师 } Let result = reverse("hello") console.log(结果)

var str = "IAMA JavaScript Developer";
var a=str.split(''), b = a.length;
for (var i=0; i<b; i++) {
    a.unshift(a.splice(1+i,1).shift())
}
a.shift();
alert(a.join(''));

ES6

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

 console.log(reverseString("Hello")); // olleH

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

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

有多种方法,你可以检查下面的,

1. 传统的for循环(递增):

函数reverseString (str) { let stringRev =""; For(令i= 0;我< str.length;我+ +){ stringRev = str[i]+stringRev; } 返回stringRev; } alert (reverseString(“Hello World !”);

2. 传统的for循环(递减):

函数反向字符串(str){ 让 revstr = “”; for(let i = str.length-1, i>=0, i--){ Revstr = Revstr+ str[i]; } 返回修订版; } alert(reverseString(“Hello World!”));

3.使用for-of循环

函数反向字符串(str){ 让 strn =“”; for(let char of str){ strn = char + strn; } 返回 STRN; } alert(reverseString(“Get Well soon”));

4. 使用forEach/高阶数组方法:

函数反向字符串(str){ 让 revSrring = “”; str.split(“”).forEach(function(char){ revSrring = char + revSrring; }); 返回转速Srring; } alert(reverseString(“Learning JavaScript”));

5. ES6标准:

函数反向字符串(str){ 让 revSrring = “”; str.split(“”).forEach(char => revSrring = char + revSrring); 返回转速Srring; } alert(reverseString(“Learning JavaScript”));

6. 最新的方式:

函数反向字符串(str){ return str.split(“”).reduce(function(revString, char){ 返回字符 + revString; }, ""); } alert(reverseString(“Learning JavaScript”));

7. 你也可以用下面的方法得到结果,

函数反向字符串(str){ return str.split(“”).reduce((revString, char)=> char + revString, “”); } alert(reverseString(“Learning JavaScript”));