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(" ")
}
}
概念:
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学习笔记】第十四章 付款处理
序列 索引 python比较神奇,可以从正面数或反着数,每一个位置都有自己的下标 切片 假设现在有一...
在这几天跟许多朋友借了不同的帐号来玩,包含了前面介绍的甚麽hostinger、godaddy、智邦云...
昨天我们了解到 JavaScript 的非同步执行方法,但有时我们想要等到 A 事件结束後,再来进行...
我们在模板中要进行计算或转换资料时computed及method通常能做到一样的效果,这麽说的话那不...
其实原本最初规画想要做Index方式的纪录,然後多增加一些没写到的面向 不过,总是计画赶不上变化 ...