--- title: Codewars刷題 11~20 tags: codewars, description: --- Codewars刷題 11~20 === 11.Remove String Spaces --- #### 移除字串中的空格 - 用``split('')``和``forEach``的解法 ```javascript= function noSpace(x){ let newString = ''; x.split('').forEach(item => item === ' ' ? newString += '' : newString += item); return newString; }; console.log(noSpace('as sss s w w e ff')); ``` - 用``split('')``和``filter()``、``join('')``的解法 ```javascript= function noSpace(x){ return x.split('').filter(item => item !== ' ').join(''); }; console.log(noSpace('as sss s w w e ff')); ``` - 用``split('')``和``join('')``的解法 ```javascript= function noSpace(x){ return x.split(' '),join(''); }; console.log(noSpace('as sss s w w e ff')); ``` <br> 12.String cleaning --- #### 將字串代入函式,把字串中的數字去除,需要保留特殊字圖```~#$%^&!@*():;"'.,?``` 以及完整的空格 ![](https://i.imgur.com/Uokw2Ew.png) - **用``.split()``、``.filter()``、``.join()``的解法** - 將字串拆成陣列後,用``.filter()``去篩選。 - 篩選條件為=> 將字串陣列一一取出,乘上``+``號。 - 原先文字字串乘上``+``號,變成NaN(篩選判斷條件false)。數字字串乘上+號,變成純數字(篩選判斷條件true)。 - ``!+value``為``+value``反向結果,因此``.filter()``只篩選陣列裡的NaN。 ```javascript= function stringClean(str){ return str.split('').filter(value => !+value ).join(''); }; console.log(stringClean('! !')); console.log(stringClean('123456789')); console.log(stringClean('This looks5 grea8t!')); ``` - **用正則表達式的解法** - 最外層一定包含// - \d:任何數字字元,等於``[0-9]`` - \D:任何非數字字元,等於``[^0-9]`` - \w:任何數字字元字母底線,等於``[A-Za-z0-9_]`` - \W:任何非數字字元字母底線,等於``[^A-Za-z0-9_]`` ```javascript= function stringClean(str){ //.replace(),用正則表達式選取,代入字串裡的字元,再用空字串取代 return str.replace(/\d/g, ''); }; console.log(stringClean('! !')); console.log(stringClean('123456789')); console.log(stringClean('This looks5 grea8t!')); ``` #### 延伸閱讀 - [String replace()](https://www.fooish.com/javascript/string/replace.html) - [Javascript Regular Expressions , 表示法](https://www.puritys.me/docs-blog/article-30-Javascript-Regular-Expressions-,-表示法.html) - [正規表達式 Regular Expression](https://ithelp.ithome.com.tw/articles/10205643) <br> 13.Stringy Strings --- #### 寫一個 function 會帶入 size 的參數,表示是幾位數,並將位數替換成 1 及 0 ,從 1 開始。 ![](https://i.imgur.com/ksOm6T7.png) - 參數size代入迴圈計算內,i取2的餘數,每次迴圈累加到變數``result`` ```javascript= function stringy(size) { let result = ''; for (let i = 1; i <= size; i++) { result += i % 2; } return result; }; console.log(stringy(4)); ``` #### 另解 - ``Array(size)``:建立size個長度的陣列。 - ``Array(4)``的``.length``等於4。陣列內容[``empty``, ``empty``, ``empty``, ``empty``]。 - ``.keys()``:會回傳一個包含陣列中的每一個索引之鍵(keys)的新 Array Iterator 物件。 - ``[...Array(size).keys()]``:把size個長度的陣列key值,解構賦值到新陣列上。 - ``.map()``再把值取出,跟2取餘數後回傳,``.join()``再重組成字串。 ```javascript= function stringy(size) { return [...Array(size).keys()].map(item => item % 2 == 0 ? 1 : 0).join('') } ``` #### 延伸閱讀 - [Array.prototype.keys()](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/keys) - [JavaScript 陣列(Array)的方法](https://ithelp.ithome.com.tw/articles/10219019) <br> 14.The Feast of Many Beasts --- #### 建立function代入兩個字串,檢查兩個字串的第一個、和最後一個字元是否相同,相同回傳``true``,不同回傳``false`` - 分別比對兩個字串的第一個字元、第二個字元是否相同 ```javascript= function feast(beast, dish) { return beast[0] === dish[0] && beast[beast.length -1 ] === dish[dish.length - 1]; }; console.log(feast('chickadee', 'chocolate cake')); ``` <br> 15.the string uppercase? --- #### 創建``String``原型方法,來查看字串是否全部都是大寫,是的話回傳true,否則回傳false - 在String下建立新的原型方法.isUpperCase ```javascript= String.prototype.isUpperCase = function() { return this == this.toUpperCase(); }; ``` - 字串型別的資料都能調用``isUpperCase``這個原型方法。 - ``console.dir(String)``可以看String所有的原型方法。 ![](https://i.imgur.com/oEdTjL3.png =50%x) ```javascript= let str = 'C'; console.log(str.isUpperCase()); //true console.dir(String); ``` #### 延伸閱讀 - [this](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Operators/this) <br> 16.Jaden Casing Strings - 首字大寫 --- ![](https://i.imgur.com/HdPAU76.png) #### 將句子裡每個「單詞」的「第一個」字母改為「大寫」 - .map()取陣列每個item第一個字元做toUpperCase,再加上.slice保留第二個字元之後 ```javascript= String.prototype.toJadenCase = function () { return this.split(' ').map(value => `${value[0].toUpperCase()}${value.slice(1)}`).join(' '); }; const str = 'may force be with you'; console.log(str.toJadenCase()); ``` <br> 17.I love you, a little , a lot, passionately ... not at all - 數花瓣 --- #### 依照函式代入的數字,選擇陣列內所屬的詞語。如果有超過 6 個花瓣,則重新開始,第七片花瓣`'I love you'`依此類推。 `I love you` `a little` `a lot` `passionately` `madly` `not at all` - 判斷代入的數字,跟陣列長度==取餘數== - 若餘數`=== 0`,用`data.length`取得物件`data`資料 - 若餘數`!== 0`,用`(nbPetals % data.length) - 1`取得物件`data`資料 ```javascript= function howMuchILoveYou(nbPetals) { const data = ['I love you', 'a little', 'a lot', 'passionately', 'madly', 'not at all']; const findIndex = nbPetals % data.length === 0 ? data.length - 1 : (nbPetals % data.length) - 1; return data[findIndex]; }; console.log(howMuchILoveYou(7)); // I love you console.log(howMuchILoveYou(14)); // a little console.log(howMuchILoveYou(21)); // a lot console.log(howMuchILoveYou(30)); // not at all ``` #### 另解 - 先將代入的數字`- 1`,再跟`data.length`取餘數。 (因為陣列`index最大值`等於`data.length - 1`) ```javascript= function howMuchILoveYou(nbPetals) { const data = ['I love you', 'a little', 'a lot', 'passionately', 'madly', 'not at all']; return data[(nbPetals - 1) % data.length]; }; ``` <br> 18.Rock Paper Scissors! - 剪刀、石頭、布 --- #### 函式代入兩組參數input1、input2,判斷input1、input2誰猜拳獲勝。 ![](https://i.imgur.com/SUkixSE.png =70%x) #### `if...else` `else...if`把猜拳的模式條列出來 - 平手的條件式`p1 === p2` - player 1 won!的條件式 `p1 === 'scissors' && p2 === 'paper' || p1 === 'rock' && p2 === 'scissors' || p1 === 'paper' && p2 === 'rock'` - player 2 won!的條件式(上面兩個條件式都相反的狀況) ```javascript= const rps = (p1, p2) => { if (p1 === p2) { return `Draw!`; } else if (p1 === 'scissors' && p2 === 'paper' || p1 === 'rock' && p2 === 'scissors' || p1 === 'paper' && p2 === 'rock') { return `Player 1 won!`; } else { return `Player 2 won!`; } }; console.log(rps('scissors', 'paper')); // Player 1 won! console.log(rps('scissors', 'rock')); // Player 2 won! ``` #### 使用物件解法 - 把Player 1贏得猜拳的方式,使用物件方式展現。 - `if`條件式把`p1`代入`rules[p1]`取得屬性值,再跟`p2`比對。 - 為`true`則Player 1 won!。 - 為`false`則Player 2 won!。 ```javascript= const rps = (p1, p2) => { if (p1 === p2) return "Draw!"; var rules = {rock: "scissors", paper: "rock", scissors: "paper"}; if (p2 === rules[p1]) { return "Player 1 won!"; } else { return "Player 2 won!"; } }; ``` #### 正則表達式解法 ```javascript= const rps = (p1, p2) => { if(p1 === p2) { return 'Draw!' }; return `Player ${/rockscissors|scissorspaper|paperrock/.test(p1+p2)? 1 : 2} won!`; } ``` <br> 19.Total amount of points - 總分數 --- **題目參數會提供 10 場比賽的比分,格式為 `x:y`。`x` 為我方分數,`y` 為對手分數,要協助計算這 10 場的對戰積分。** **積分規則如下:** `x > y 我方勝的話,積分 + 3` `x < y 我方輸的話,積分 + 0` `x = y 平手的話,積分 + 1` - 用`.forEach()`將`item`(比分)取出,`.split(':')`再把比分**拆分成**陣列。 ![](https://i.imgur.com/YHdsZ1n.png) - 再分別`item.split(':')[0]`取得x分數 ,`item.split(':')[0]`取得y分數。 - 因為取得比數資料的型別為`string`,所以需要轉型成`number`。 - 所以前面加`+`,變成 `+item.split(':')[0]`,把string型別數字轉型number型別。 :::success **string型別**的數字比較判斷時,是用**ASCII編碼**。 只有**個位數**string數字可以直接比較大小,**十位數(含)以上**string數字需要**轉型number**後才可比較。 ```javascript= '3' > '14' // true ``` ::: ```javascript= const games = ["4:13", "2:0", "3:0", "2:0", "1:2", "2:3", "4:1", "1:2", "1:2", "4:0"]; function points(games) { let pointsTotal = 0; games.forEach(item => +item.split(':')[0] > +item.split(':')[1] ? pointsTotal += 3 : +item.split(':')[0] === +item.split(':')[1] ? pointsTotal += 1 : pointsTotal += 0); return pointsTotal; }; console.log(points(games)); // 15 ``` <br> 20.Categorize New Member - 分類新成員 --- **西郊槌球俱樂部把會員成"Senior"和"Open"兩類,如果是Senior,你的年紀必須至少55歲以上,且殘障等級必須高於7,否則就是Open** ![](https://i.imgur.com/GQzugPz.png) - 用`.map()`把物件的`item`取出。 - 取出的item物件,`item[0]`取年紀、`item[1]`取差點,用三元運算子`item[0] >= 55 && item[1] > 7 ? 'Senior' : 'Open'`回傳相對應的結果。 ```javascript= const data = [[18, 20], [45, 2], [61, 12], [37, 6], [21, 21], [78, 9]]; function openOrSenior(data) { return data.map(item => item[0] >= 55 && item[1] > 7 ? 'Senior' : 'Open'); }; console.log(openOrSenior(data)); ``` **另解:** - 用`.map()`把物件的`item`取出,並且以陣列形式拆解,並給予`age`、`handicap`的名稱。 ```javascript= function openOrSenior(data){ return data.map(([age, handicap]) => (age > 54 && handicap > 7) ? 'Senior' : 'Open'); } ```