JavaScript - 反转句子中的单词

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

最后一个单词没有被反转并且没有在最终结果中输出。不确定缺少什么。

1
https://dev59.com/DnNA5IYBdhLWcg3wcddk - user3272018
2
它无法反转,因为最后一个单词后面没有空格字符。 - Lye Fish
这是因为最后一个单词只被推入a[i]中,但由于出了for循环而没有被反转。 - shreyansh
除了这个实现中的错误,它过于复杂了。使用分割、反转和连接就可以完成任务。 - AJF
4个回答

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("")+" ";

0

试试这个:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接