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(" ")
  }
}

概念:

  1. 先将字串全部拆成一个个字,并存於array中。
  2. 将Array内的每个字逐一检查是否长度有大於等於5
  3. 若长度大於等於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/


<<:  【左京淳的JAVA WEB学习笔记】第十四章 付款处理

>>:  安全玻璃(Safety Glass)

(),[] -- 列表与元组

序列 索引 python比较神奇,可以从正面数或反着数,每一个位置都有自己的下标 切片 假设现在有一...

第二章 空间选择困难症

在这几天跟许多朋友借了不同的帐号来玩,包含了前面介绍的甚麽hostinger、godaddy、智邦云...

Day 29 JavaScript : promise

昨天我们了解到 JavaScript 的非同步执行方法,但有时我们想要等到 A 事件结束後,再来进行...

Day8 Vue Computed vs Method

我们在模板中要进行计算或转换资料时computed及method通常能做到一样的效果,这麽说的话那不...

简报版-第十三章-从各式诈骗钓鱼邮件等社交工程手法看问题

其实原本最初规画想要做Index方式的纪录,然後多增加一些没写到的面向 不过,总是计画赶不上变化 ...