问题
Please refer - https://jsfiddle.net/jy5p509c/
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);
The last word does not reverse and is not outputted in the final result. Not sure what is missing.
回答1:
It problem is your if(a[i] == " ")
condition is not satisfied for the last word
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))
You can also try a shorter
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))
回答2:
I don't know wich one is the best answer I'll live you mine and let you decide, here it is :
console.log( 'who all are coming to the party and merry around in somewhere'.split('').reverse().join('').split(" ").reverse().join(" "));
回答3:
Add the following line before console log, you will get as expected
res+= resarr.reverse().join("")+" ";
回答4:
Try this:
var a = "who all are coming to the party and merry around in somewhere";
//split the string in to an array of words
var sp = a.split(" ");
for (i = 0; i < sp.length; i++) {
//split the individual word into an array of char, reverse then join
sp[i] = sp[i].split("").reverse().join("");
}
//finally, join the reversed words back together, separated by " "
var res = sp.join(" ");
document.body.appendChild(document.createTextNode(res))
来源:https://stackoverflow.com/questions/30865704/javascript-reverse-words-in-a-sentence