请参考——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))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)