給定陣列 ["cat", "dog", "reindeer", "penguin", "crocodile"],列印至少有 4 個輔音的單詞。
我不知道該怎么做。
uj5u.com熱心網友回復:
下面的注釋代碼可以幫助您:
const animals = ["cat", "dog", "reindeer", "penguin", "crocodile"]
const vowels = ['a', 'e', 'i', 'o', 'u']
animals.forEach(animal=>{
let counter=0
//spliting the word in letters
animal.split('').forEach(letter=>{
//checking if the letter is really a letter and if it is not a vowel
if(letter.toLocaleLowerCase()>='a'&&letter.toLocaleLowerCase()<='z'&&!vowels.some(v=>v===letter.toLocaleLowerCase()))
counter
})
if(counter>=4)
console.log(animal)
})
uj5u.com熱心網友回復:
使用Stringmatch()方法進行模式匹配,以及Array.prototype。filter()對于item的條件篩選,我們可以寫一個簡潔的one-liner:
> const animals = ["cat", "dog", "reindeer", "penguin", "crocodile"]
> animals.filter( animal => animal.match(/[^aeiou]/gi).length >= 4)
["reindeer", "penguin", "crocodile"]
regex盡可能多地學習。這里有一些資源:快速概覽、詳細演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/346647.html
標籤:javascript 数组
上一篇:賦值運算子左側的遞增陣列索引
