// 方法一 正则function reverse(str){ var reg = /\w+/g; var arr = str.match(reg); var str = ""; var len = arr.length; for(var i=len-1;i>0;i++){ str = str+arr[i]+" "; } str+=arr[0]; return str;}// 方法二 递减循环遍历String.prototype.split = String.prototype.split || function(target){ var arr = []; var temp = ""; for (var i=0;i<this.length;i++) { var ch = this.charAt(i); if(ch == target){ arr.push(temp); temp = ""; }else{ temp += ch; } } arr.push(temp); return arr;}function reverse(str){ var arr = str.split(" "); var newStr = "" var len = arr.length; for(var i=len-1;i>0;i++){ newStr = newStr+arr[i]+" "; } newStr+=arr[0]; return newStr;}
2 回答
千秋此意
TA贡献158条经验 获得超187个赞
//还是用的正则,如果要追求效率的话直接用split(' ').reverse().join(' ')不就好了么... function reverse(str) { var re = /\b\w+\b/g; var matches; return function(tempStr) { return (matches = re.exec(str)) !== null ? arguments.callee(matches + ' ' + tempStr) : tempStr.replace(/\s$/,''); }(''); } var result = reverse('I am a coder'); console.log(result);
qq_包包世界我专业_0
TA贡献14条经验 获得超1个赞
方法三
var btn = " I am a coder ",
str = "",
arr = [];
for (var i = 0; i < btn.length; i++) {
var data = btn[i];
if (data != " ") {
str += data;
if (i != btn.length - 1) {
continue;
}
}
if (str != "") {
arr.push(str);
str = "";
}
}
var s=""
for (var i = arr.length - 1, arr2; arr2 = arr[i--];) {
s += arr2+" ";
}
console.log(s);
添加回答
举报
0/150
提交
取消