Javascript - 在句子中反转单词

Javascript - Reverse words in a sentence

请参考- 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);

最后一个字不反转,不在最终结果中输出。不确定缺少什么。

问题是你的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))

我不知道哪一个是最好的答案我会用你自己的方式让你决定,这里是:

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

在控制台日志前添加以下行,您将得到预期的结果

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

试试这个:

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))