gpt4 book ai didi

Javascript - 在句子中反转单词

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:02:23 24 4
gpt4 key购买 nike

请引用- 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))

关于Javascript - 在句子中反转单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30865704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com