Home > Web Front-end > JS Tutorial > Easy way to flip word order

Easy way to flip word order

一个新手
Release: 2017-10-11 10:01:24
Original
1415 people have browsed it


Output I am boy as boy am I

First convert I am boy to yob ma I, exchange str[0] with str[len-1] order, the space complexity is O(1). Then apply the same method to flip each word in yob ma I.

function reverse(str) {
   var strArr = str.split("");   
   var len= Math.floor(str.length/2),strLen = str.length-1;   
   for(var i=0;i<len;i++){     
   var temp = strArr[i];
     strArr[i] = strArr[strLen - i];
     strArr[strLen - i] = temp;
   }   return strArr.join("");
}function reverseWord(str) {
    str = reverse(str);    
    var strArr = str.split(" ");    
    var newArr = strArr.map(function (item) {
      return  reverse(item);
    });    return newArr.join(" ");
}


console.log(reverseWord("I am boy"));
Copy after login

(1) Note that the string needs to be converted into a character array, because the array is a reference type, and exchange with each other can change the original value, but strings cannot. For example:

var str = "boy";str[0].=str[2];
console.log(str);
Copy after login

(2) Question: A new array newArr

is introduced

The above is the detailed content of Easy way to flip word order. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template