JavaScript 反转字符串中每个单词的字母顺序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18382930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript reverse the order of letters for each word in a string
提问by Alessandro
I am trying to get around the following but no success:
我试图解决以下问题但没有成功:
var string = "erehT era a tsav rebmun fo secruoser rof gninrael erom tpircsavaJ";
var x = string.split(" ");
for(i=0; i<=x.length; i++){
var element = x[i];
}
element now represents each word inside the array. I now need to reverse not the order of the words but the order of each letter for each word.
element 现在表示数组中的每个单词。我现在需要的不是颠倒单词的顺序,而是颠倒每个单词的每个字母的顺序。
回答by Praveen Lobo
var string = "erehT era a tsav rebmun fo secruoser rof gninrael erom tpircsavaJ";
// you can split, reverse, join " " first and then "" too
string.split("").reverse().join("").split(" ").reverse().join(" ")
Output: "There are a vast number of resources for learning more Javascript"
输出:“有大量资源可用于学习更多 Javascript”
回答by plalx
You can do it like this using Array.prototype.map
and Array.prototype.reverse
.
您可以使用Array.prototype.map
and这样做Array.prototype.reverse
。
var result = string.split(' ').map(function (item) {
return item.split('').reverse().join('');
}).join(' ');
what's the map function doing there?
地图功能在那里做什么?
It traverses the array created by splitting the initial string and calls the function (item)
we provided as argument for each elements. It then takes the return value of that function and push it in a new array. Finally it returns that new array, which in our example, contains the reversed words in order.
它遍历通过拆分初始字符串创建的数组,并function (item)
为每个元素调用我们提供的参数。然后它获取该函数的返回值并将其推送到一个新数组中。最后它返回那个新数组,在我们的例子中,它按顺序包含颠倒的单词。
回答by Mwiza
You can do the following:
您可以执行以下操作:
let stringToReverse = "tpircsavaJ";
stringToReverse.split("").reverse().join("").split(" ").reverse().join(" ")
//let keyword allows you declare variables in the new ECMAScript(JavaScript)
//let 关键字允许你在新的 ECMAScript(JavaScript) 中声明变量
回答by Junu
You can do the following.
您可以执行以下操作。
var string = "erehT era a tsav rebmun fo secruoser rof gninrael erom tpircsavaJ";
arrayX=string.split(" ");
arrayX.sort().reverse();
var arrayXX='';
arrayX.forEach(function(item){
items=item.split('').sort().reverse();
arrayXX=arrayXX+items.join('');
});
document.getElementById('demo').innerHTML=arrayXX;