Array.prototype.push = function( element ) {
this[ this.length ] = element;
};
Array.prototype.pop = function() {
var tmp = this[ this.length - 1 ];
this.length = this.length - 1 ;
return tmp;
};
function reverse ( str ) {
var arr = [];
var start = 0;
for (var i = 0; i < str.length; i++) {
if ( str[ i ] === " " ) {
arr.push( str.slice( start , i ) );
start = i + 1;
}
};
if ( start !== str.length )
arr.push( str.slice( start , str.length ) );
var returnStr = "";
while( arr.length>0 )
returnStr = returnStr + " " + arr.pop();
return returnStr.slice(1);
}
function reverse2 ( str ) {
var arr = [];
var returnStr = "";
var popArr = function () {
while( arr.length > 0 )
returnStr = returnStr + arr.pop();
returnStr = returnStr + " ";
};
for (var i = 0; i < str.length; i++) {
if ( str[i] !== " " )
arr.push( str[ i ] );
else
popArr();
};
if ( str[ str.length -1 ] !== " " )
popArr();
return returnStr.slice( 0 , returnStr.length - 1 );
}
//test
var str = "I am a student.";
reverse( str );
reverse2( str );
js 翻转字符串
最新推荐文章于 2023-06-26 18:29:31 发布