Home >Web Front-end >JS Tutorial >Easy way to flip word order
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"));
(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);
(2) Question: A new array newArr
is introducedThe 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!