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


当前回答

这样的事情应该遵循最佳实践:

(function(){ 'use strict'; var str = "testing"; //using array methods var arr = new Array(); arr = str.split(""); arr.reverse(); console.log(arr); //using custom methods var reverseString = function(str){ if(str == null || str == undefined || str.length == 0 ){ return ""; } if(str.length == 1){ return str; } var rev = []; for(var i = 0; i < str.length; i++){ rev[i] = str[str.length - 1 - i]; } return rev; } console.log(reverseString(str)); })();

其他回答

添加的反向字符串没有循环,它是通过递归工作。

函数反向(y) { 如果(y)。Length ==1 || . Length == 0){ 返回y; } 返回y.split(”)[y。长度- 1]+反向(y。片(0,y.length-1)); } console.log(反向(“Hello”));

var str = 'sample string';
[].map.call(str, function(x) {
  return x;
}).reverse().join('');

OR

var str = 'sample string';
console.log(str.split('').reverse().join(''));

//输出:“gnirts elpmas”

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

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

好的,很简单,你可以创建一个简单的循环函数来为你反向字符串,而不需要使用reverse(), charAt()等,就像这样:

例如,你有这样一个字符串:

var name = "StackOverflow";

创建一个这样的函数,我称之为reverseString…

function reverseString(str) {
  if(!str.trim() || 'string' !== typeof str) {
    return;
  }
  let l=str.length, s='';
  while(l > 0) {
    l--;
    s+= str[l];
  }
  return s;
}

你可以这样称呼它:

reverseString(name);

结果是:

"wolfrevOkcatS"

下面是一个基本的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'