猿问

js将“I am a coder”反转成 “coder a am I”,不许用split,join,subString,reverse;求解方法三

// 方法一 正则

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;

}


qq_爱米休_03662495
浏览 2008回答 2
2回答

千秋此意

//还是用的正则,如果要追求效率的话直接用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

方法三        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);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答