Javascript-句子中的反词 [英] Javascript - Reverse words in a sentence
本文介绍了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);
最后一个字不会反转,并且不会在最终结果中输出.不知道丢失了什么.
The last word does not reverse and is not outputted in the final result. Not sure what is missing.
推荐答案
问题是您的 if(a [i] ==")
条件不满足最后一个单词
It problem is your if(a[i] == " ")
condition is not satisfied for the last word
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-句子中的反词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文