当一个字符串被传递给一个带有返回语句的函数时,你如何在JavaScript中反转它,而不使用内置函数(.reverse(), . charat()等)?
当前回答
以下是可以用来实现字符串反转的四种最常用方法
给定一个字符串,返回一个新字符串 字符顺序
问题的多种解决方案
//reverse('apple') === 'leppa'
//reverse('hello') === 'olleh'
//reverse('Greetings!') === '!sgniteerG'
// 1. First method without using reverse function and negative for loop
function reverseFirst(str) {
if(str !== '' || str !==undefined || str !== null) {
const reversedStr = [];
for(var i=str.length; i>-1; i--) {
reversedStr.push(str[i]);
}
return reversedStr.join("").toString();
}
}
// 2. Second method using the reverse function
function reverseSecond(str) {
return str.split('').reverse().join('');
}
// 3. Third method using the positive for loop
function reverseThird(str){
const reversedStr = [];
for(i=0; i<str.length;i++) {
reversedStr.push(str[str.length-1-i])
}
return reversedStr.join('').toString();
}
// 4. using the modified for loop ES6
function reverseForth(str) {
const reversedStr = [];
for(let character of str) {
reversedStr = character + reversedStr;
}
return reversedStr;
}
// 5. Using Reduce function
function reverse(str) {
return str.split('').reduce((reversed, character) => {
return character + reversed;
}, '');
}
其他回答
你不能,因为JS字符串是不可变的。短的非就地解决方案
[...str].reverse().join``
let str = "Hello World!"; Let r =[…str].reverse().join ' '; console.log (r);
我想,这对你有用
function reverse(str){
str = str.split("").reverse().join("").split(" ").reverse().join(" ");
console.log(str)
}
添加到String原型是理想的(只是以防它被添加到核心JS语言中),但你首先需要检查它是否存在,如果不存在就添加它,如下所示:
String.prototype.reverse = String.prototype.reverse || function () {
return this.split('').reverse().join('');
};
详细分析和十种不同的方法来反转字符串和他们的性能细节。
http://eddmann.com/posts/ten-ways-to-reverse-a-string-in-javascript/
这些实现的性能:
每个浏览器的最佳执行实现
Chrome 15 -实现1和6 Firefox 7 -实现6 IE 9 -实现4 Opera 12 -实现9
以下是这些实现:
实现1:
function reverse(s) {
var o = '';
for (var i = s.length - 1; i >= 0; i--)
o += s[i];
return o;
}
实现2:
function reverse(s) {
var o = [];
for (var i = s.length - 1, j = 0; i >= 0; i--, j++)
o[j] = s[i];
return o.join('');
}
实现3:
function reverse(s) {
var o = [];
for (var i = 0, len = s.length; i <= len; i++)
o.push(s.charAt(len - i));
return o.join('');
}
实现4:
function reverse(s) {
return s.split('').reverse().join('');
}
实现5:
function reverse(s) {
var i = s.length,
o = '';
while (i > 0) {
o += s.substring(i - 1, i);
i--;
}
return o;
}
实现6:
function reverse(s) {
for (var i = s.length - 1, o = ''; i >= 0; o += s[i--]) { }
return o;
}
实现7:
function reverse(s) {
return (s === '') ? '' : reverse(s.substr(1)) + s.charAt(0);
}
实现8:
function reverse(s) {
function rev(s, len, o) {
return (len === 0) ? o : rev(s, --len, (o += s[len]));
};
return rev(s, s.length, '');
}
实现9:
function reverse(s) {
s = s.split('');
var len = s.length,
halfIndex = Math.floor(len / 2) - 1,
tmp;
for (var i = 0; i <= halfIndex; i++) {
tmp = s[len - i - 1];
s[len - i - 1] = s[i];
s[i] = tmp;
}
return s.join('');
}
实现10
function reverse(s) {
if (s.length < 2)
return s;
var halfIndex = Math.ceil(s.length / 2);
return reverse(s.substr(halfIndex)) +
reverse(s.substr(0, halfIndex));
}
实现11
var reverser = function(str){
let string = str.split('');
for(i=0;i<string.length;i++){
debugger;
string.splice(i,0,string.pop());
}
console.log(string.join())
}
reverser('abcdef')
看来我已经迟到3年了…
不幸的是,正如已经指出的那样,你不能。参见JavaScript字符串是不可变的吗?我需要一个“字符串生成器”在JavaScript?
你能做的下一个最好的事情是创建一个“视图”或“包装器”,它接受一个字符串并重新实现你正在使用的字符串API的任何部分,但假装字符串是反向的。例如:
var identity = function(x){return x};
function LazyString(s) {
this.original = s;
this.length = s.length;
this.start = 0; this.stop = this.length; this.dir = 1; // "virtual" slicing
// (dir=-1 if reversed)
this._caseTransform = identity;
}
// syntactic sugar to create new object:
function S(s) {
return new LazyString(s);
}
//We now implement a `"...".reversed` which toggles a flag which will change our math:
(function(){ // begin anonymous scope
var x = LazyString.prototype;
// Addition to the String API
x.reversed = function() {
var s = new LazyString(this.original);
s.start = this.stop - this.dir;
s.stop = this.start - this.dir;
s.dir = -1*this.dir;
s.length = this.length;
s._caseTransform = this._caseTransform;
return s;
}
//We also override string coercion for some extra versatility (not really necessary):
// OVERRIDE STRING COERCION
// - for string concatenation e.g. "abc"+reversed("abc")
x.toString = function() {
if (typeof this._realized == 'undefined') { // cached, to avoid recalculation
this._realized = this.dir==1 ?
this.original.slice(this.start,this.stop) :
this.original.slice(this.stop+1,this.start+1).split("").reverse().join("");
this._realized = this._caseTransform.call(this._realized, this._realized);
}
return this._realized;
}
//Now we reimplement the String API by doing some math:
// String API:
// Do some math to figure out which character we really want
x.charAt = function(i) {
return this.slice(i, i+1).toString();
}
x.charCodeAt = function(i) {
return this.slice(i, i+1).toString().charCodeAt(0);
}
// Slicing functions:
x.slice = function(start,stop) {
// lazy chaining version of https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice
if (stop===undefined)
stop = this.length;
var relativeStart = start<0 ? this.length+start : start;
var relativeStop = stop<0 ? this.length+stop : stop;
if (relativeStart >= this.length)
relativeStart = this.length;
if (relativeStart < 0)
relativeStart = 0;
if (relativeStop > this.length)
relativeStop = this.length;
if (relativeStop < 0)
relativeStop = 0;
if (relativeStop < relativeStart)
relativeStop = relativeStart;
var s = new LazyString(this.original);
s.length = relativeStop - relativeStart;
s.start = this.start + this.dir*relativeStart;
s.stop = s.start + this.dir*s.length;
s.dir = this.dir;
//console.log([this.start,this.stop,this.dir,this.length], [s.start,s.stop,s.dir,s.length])
s._caseTransform = this._caseTransform;
return s;
}
x.substring = function() {
// ...
}
x.substr = function() {
// ...
}
//Miscellaneous functions:
// Iterative search
x.indexOf = function(value) {
for(var i=0; i<this.length; i++)
if (value==this.charAt(i))
return i;
return -1;
}
x.lastIndexOf = function() {
for(var i=this.length-1; i>=0; i--)
if (value==this.charAt(i))
return i;
return -1;
}
// The following functions are too complicated to reimplement easily.
// Instead just realize the slice and do it the usual non-in-place way.
x.match = function() {
var s = this.toString();
return s.apply(s, arguments);
}
x.replace = function() {
var s = this.toString();
return s.apply(s, arguments);
}
x.search = function() {
var s = this.toString();
return s.apply(s, arguments);
}
x.split = function() {
var s = this.toString();
return s.apply(s, arguments);
}
// Case transforms:
x.toLowerCase = function() {
var s = new LazyString(this.original);
s._caseTransform = ''.toLowerCase;
s.start=this.start; s.stop=this.stop; s.dir=this.dir; s.length=this.length;
return s;
}
x.toUpperCase = function() {
var s = new LazyString(this.original);
s._caseTransform = ''.toUpperCase;
s.start=this.start; s.stop=this.stop; s.dir=this.dir; s.length=this.length;
return s;
}
})() // end anonymous scope
演示:
> r = S('abcABC')
LazyString
original: "abcABC"
__proto__: LazyString
> r.charAt(1); // doesn't reverse string!!! (good if very long)
"B"
> r.toLowerCase() // must reverse string, so does so
"cbacba"
> r.toUpperCase() // string already reversed: no extra work
"CBACBA"
> r + '-demo-' + r // natural coercion, string already reversed: no extra work
"CBAcba-demo-CBAcba"
最重要的是——下面是用纯数学来完成的,每个角色只访问一次,而且是在必要的时候:
> 'demo: ' + S('0123456789abcdef').slice(3).reversed().slice(1,-1).toUpperCase()
"demo: EDCBA987654"
> S('0123456789ABCDEF').slice(3).reversed().slice(1,-1).toLowerCase().charAt(3)
"b"
如果应用于一个非常大的字符串,如果您只取其中相对较小的部分,则可以节省大量的时间。
Whether this is worth it (over reversing-as-a-copy like in most programming languages) highly depends on your use case and how efficiently you reimplement the string API. For example if all you want is to do string index manipulation, or take small slices or substrs, this will save you space and time. If you're planning on printing large reversed slices or substrings however, the savings may be small indeed, even worse than having done a full copy. Your "reversed" string will also not have the type string, though you might be able to fake this with prototyping.
The above demo implementation creates a new object of type ReversedString. It is prototyped, and therefore fairly efficient, with almost minimal work and minimal space overhead (prototype definitions are shared). It is a lazy implementation involving deferred slicing. Whenever you perform a function like .slice or .reversed, it will perform index mathematics. Finally when you extract data (by implicitly calling .toString() or .charCodeAt(...) or something), it will apply those in a "smart" manner, touching the least data possible.
注意:上面的字符串API是一个例子,可能不能完美地实现。你也可以只使用你需要的1-2个函数。
推荐文章
- Javascript数组搜索和删除字符串?
- 如何复制对象属性在另一个对象?
- 如何绕过Access-Control-Allow-Origin?
- 我如何使用Node.js Crypto创建HMAC-SHA1哈希?
- JavaScript获取滚动窗口的X/Y位置
- “文本”和新字符串(“文本”)之间的区别是什么?
- JavaScript中不带else的三元运算符
- 如何检查对象是否在JavaScript中有任何属性?
- iFrame src变化事件检测?
- Java中字符串的不可变性
- 为什么Oracle 9i将空字符串视为NULL?
- 我如何在网页上动画文本的绘图?
- 对“URL”执行“createObjectURL”失败:
- 如何在package.json中使用“main”参数?
- 为什么在Java 8中String.chars()是整数流?