CodeWars : 新手村练等纪录03- Stop gninnipS My sdroW!

Stop gninnipS My sdroW!

等级:6kyu

原始题目

Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (like the name of this kata).
Strings passed in will consist of only letters and spaces.
Spaces will be included only when more than one word is present.

Example:

spinWords("Hey fellow warriors") => "Hey wollef sroirraw" spinWords("This is a test") => "This is a test" spinWords("This is another test") => "This is rehtona test"

中翻:字串中任何一个字的长度大于或等于5时则反转该字,反之则输出一样的字。

自解:

export class Kata {  static spinWords(words: string) {    let arr = words.split(" ");    arr.forEach((e,index) => {      if(e.length >= 5 ){        let reverse = e.split('').reverse().join('');        arr.splice(index,1,reverse)      }    })    return arr.join(" ")  }}

概念:

先将字串全部拆成一个个字,并存于array中。将Array内的每个字逐一检查是否长度有大于等于5若长度大于等于5的,找到该字在Array中的index,并透过splice方法将该值换成reverse过后的值。
(splice的使用请见下方参考资料)

他解:

author: joewoodhouse

export class Kata {  static spinWords(words: string) {    return words      .split(' ') // Split words up      .map((w: string) => w.length >= 5 ? w.split('').reverse().join('') : w)      .join(' '); // Put them back together  }}

透过一连串方法,一次将资料处理完毕后直接回传,非常精简~
补充w.length >= 5 ? w.split('').reverse().join('') : w
此写法为Ternary Operator (三元运算子),可以将if else精简表达出来,有兴趣的可以查看看
https://catforcode.com/ternary-operators/

此次题目使用到的方法和参考网址:

array.split()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

array.splice() 可以藉由删除既有元素并/或加入新元素来改变一个阵列的内容。
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

(另外补充)三种reverse string的方法
https://www.freecodecamp.org/news/how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb/


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章