[JS Practice] Reverse words(反转字符)

Title :

Reverse words(反转字符)

Description:

Write a reverseWords function that accepts a string a parameter, and reverses each word in the string.

Example:

reverseWords("This is an example!"); // returns  "sihT si na !elpmaxe"

My solution :

function reverseWords(str) {
 var strArr = str.split(" "); // Split string by whitespace <a>通过空白字符切割原来的字符</a>
 var retArr = []; // Init array <a>初始化一个空数组</a>
 strArr.forEach(function(element) {
   var word = element.split("").reverse().join(""); // str to arr and then reverse  <a>把字符转化成数组 然后</a><a>反转</a>
   retArr.push(word);
 });
 return retArr.join(" ");
}

此练习的重点在于考察javascript中Array的一个基础方法reverse的使用。

Ref. from codewars

Advertisements

One comment on “[JS Practice] Reverse words(反转字符)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s