当一个字符串被传递给一个带有返回语句的函数时,你如何在JavaScript中反转它,而不使用内置函数(.reverse(), . charat()等)?
当前回答
如果你不想使用任何内置功能。试试这个
var string = 'abcdefg';
var newstring = '';
for(let i = 0; i < string.length; i++){
newstring = string[i] += newstring;
}
console.log(newstring);
其他回答
没有内置方法?鉴于Javascript中的字符串是不可变的,您可能希望使用内置的方法,如split、join等。但这里有两种不使用这些方法的方法:
function ReverseString(str) {
var len = str.length;
var newString = [];
while (len--) {
newString.push(str[len]);
}
return newString.join('');
}
console.log(ReverseString('amgod')) //dogma
function RecursiveStringReverse(str, len) {
if (len === undefined)
len = str.length - 1;
if (len > 0)
return str[len] + RecursiveReverse(str, --len);
return str[len];
}
console.log(RecursiveStringReverse('Hello, world!'))// !dlrow ,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
这样的事情应该遵循最佳实践:
(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)); })();
function reverseString(string) {
var reversedString = "";
var stringLength = string.length - 1;
for (var i = stringLength; i >= 0; i--) {
reversedString += string[i];
}
return reversedString;
}
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;
}
推荐文章
- 克隆对象没有引用javascript
- 验证字符串是否为正整数
- 如何获得一个键/值JavaScript对象的键
- 什么时候JavaScript是同步的?
- 我如何分割一个字符串由一个多字符分隔符在c# ?
- 如何删除Python中的前导空白?
- 如何在Typescript中解析JSON字符串
- Javascript reduce()在对象
- 在angularJS中& vs @和=的区别是什么
- 错误"Uncaught SyntaxError:意外的标记与JSON.parse"
- JavaScript中的querySelector和querySelectorAll vs getElementsByClassName和getElementById
- 给一个数字加上st, nd, rd和th(序数)后缀
- 如何以编程方式触发引导模式?
- 如何分割逗号分隔的字符串?
- Java字符串—查看字符串是否只包含数字而不包含字母