2015-06-16 28 views
3

請參考 - https://jsfiddle.net/jy5p509c/的Javascript - 反向詞在句子中

var a = "who all are coming to the party and merry around in somewhere"; 

res = ""; resarr = []; 

for(i=0 ;i<a.length; i++) { 

if(a[i] == " ") { 
    res+= resarr.reverse().join("")+" "; 
    resarr = []; 
} 
else { 
    resarr.push(a[i]); 
} 
} 
console.log(res); 

最後一個字不反轉,並在最後的結果不輸出。不知道缺少什麼。

+1

http://stackoverflow.com/questions/958908/how-do-you-reverse-a-string-in-place-in-javascript – user3272018

+2

它不會逆轉,因爲沒有空格字符後最後一個字。 –

+0

這是因爲最後一句話只是在[i]中被推入,但自從出現for循環後就沒有被反轉 – shreyansh

回答

10

它的問題是你的if(a[i] == " ")條件不滿足的最後一個字

var a = "who all are coming to the party and merry around in somewhere"; 
 

 
res = ""; 
 
resarr = []; 
 

 
for (i = 0; i < a.length; i++) { 
 
    if (a[i] == " " || i == a.length - 1) { 
 
    res += resarr.reverse().join("") + " "; 
 
    resarr = []; 
 
    } else { 
 
    resarr.push(a[i]); 
 
    } 
 
} 
 

 
document.body.appendChild(document.createTextNode(res))


您也可以嘗試使用較短

var a = "who all are coming to the party and merry around in florida"; 
 

 
var res = a.split(' ').map(function(text) { 
 
    return text.split('').reverse().join('') 
 
}).join(' '); 
 

 
document.body.appendChild(document.createTextNode(res))

1

我不知道至極一個是最好的答案,我會住你我讓你決定,那就是:

console.log('who all are coming to the party and merry around in somewhere'.split('').reverse().join('').split(" ").reverse().join(" ")); 
0

控制檯日誌之前添加以下行,你會得到如預計

res+= resarr.reverse().join("")+" ";