请引用 - 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))

关于Javascript - 反转句子中的单词,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30865704/

10-12 06:30