Javascript - 句子中的反向词

时间:2015-06-16 11:00:20

标签: javascript arrays reverse

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

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

4 个答案:

答案 0 :(得分: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 :(得分:1)

我不知道哪一个是最好的答案我会活在你的身边让你决定,这里是:

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

答案 2 :(得分:0)

在控制台日志之前添加以下行,您将按预期获得

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

答案 3 :(得分: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))