微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Javascript – 在句子中反转单词

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐