我有以下列表,并希望颠倒单词的顺序,而不是单词中每个字母的顺序。我目前有这个,但它是反转每个字母,而不是单词的顺序。
JS:
let items = ["Litte Bike, Tall Tree, Toy Car, Fast Car"].toString();
myArray.split("").reverse().join('')
当前输出:
raC tsaF ,raC yoT ,eerT llaT ,ekiB ettiL
所需的输出:
Bike Litte
Tree Tall
Car Toy
Car Fast
答案 0 :(得分:6)
您要先用逗号分割,然后再对新项目数组中的每个单词进行分割,然后颠倒这些项目。
您不想颠倒整个过程。
let items = ["Litte Bike, Tall Tree, Toy Car, Fast Car"].toString();
let result = items.split(',').map(item => item.split(' ').reverse().join(' ').trim());
console.log(result);
答案 1 :(得分:1)
尝试一下
let items = ["Litte Bike, Tall Tree, Toy Car, Fast Car"];
let revItems = items.map(item => item.split(" ").reverse().join(" "));
console.log(revItems.reverse())
答案 2 :(得分:0)
正如其他人所述,您必须先拆分元素,然后再拆分每个元素中的各个空格,然后反向打印。
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
p {
margin: 0px !important;
padding: 0px !important;
border: 0px !important;
}
</style>
<script type="text/javascript">
function foo() {
let items = ["Litte Bike,Tall Tree,Toy Car,Fast Car"].toString().replace(', ',','); //replace the spaces in the string between separations
var myarray = items.split(','); //separate all the individual items
for (var i = 0; i < myarray.length; i++) { //for each item, split on the space in between words
var subArray = myarray[i].split(" ");
//i ignore errors
console.log(subArray[1] + " " + subArray[0]); //print the order reversed.
}
}
</script>
</head>
<body onload="foo();">
</body>
</html>