gop*_*rao 3 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);
Run Code Online (Sandbox Code Playgroud)
最后一个字不会反转,也不会在最终结果中输出.不确定缺少什么.
Aru*_*hny 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))Run Code Online (Sandbox Code Playgroud)
你也可以尝试更短的时间
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))Run Code Online (Sandbox Code Playgroud)