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


当前回答

使用内置函数反转字符串

函数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('你好'));

其他回答

String.prototype.reverse_string=function() {return this.split("").reverse().join("");}

or

String.prototype.reverse_string = function() {
    var s = "";
    var i = this.length;
    while (i>0) {
        s += this.substring(i-1,i);
        i--;
    }
    return s;
}
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”

我认为String.prototype.reverse是解决这个问题的好方法; 代码如下;

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

var str = 'this is a good example for string reverse';
str.reverse();
-> "esrever gnirts rof elpmaxe doog a si siht";
word.split('').reduce((acc, curr) => curr+""+acc)

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