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


当前回答

另一个变体(它在IE中工作吗?):

String.prototype.reverse = function() {
    for (i=1,s=""; i<=this.length; s+=this.substr(-i++,1)) {}
    return s;
}

编辑:

这是不使用内置函数的:

String.prototype.reverse = function() {
    for (i=this[-1],s=""; i>=0; s+=this[i--]) {}
    return s;
}

注意:this[-1]保存字符串的长度。

然而,不可能将字符串反向,因为赋值给 单个数组元素不能与String对象(protected?)一起工作。也就是说,你可以赋值,但结果字符串不会改变。

其他回答

另一个变体(它在IE中工作吗?):

String.prototype.reverse = function() {
    for (i=1,s=""; i<=this.length; s+=this.substr(-i++,1)) {}
    return s;
}

编辑:

这是不使用内置函数的:

String.prototype.reverse = function() {
    for (i=this[-1],s=""; i>=0; s+=this[i--]) {}
    return s;
}

注意:this[-1]保存字符串的长度。

然而,不可能将字符串反向,因为赋值给 单个数组元素不能与String对象(protected?)一起工作。也就是说,你可以赋值,但结果字符串不会改变。

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

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(str) { 返回str.split(”)。reduce((rev, currentChar) => currentChar + rev, "); } console.log(反向('苹果')); console.log(反向('你好')); console.log(反向(“问候!”);

使用Array函数,

String.prototype.reverse = function(){
    return [].reduceRight.call(this, function(last, secLast){return last + secLast});
}

如果你不想使用任何内置功能。试试这个

var string = 'abcdefg';
var newstring = '';

for(let i = 0; i < string.length; i++){
    newstring = string[i] += newstring;
}

console.log(newstring);