我正在嘗試撰寫一個接受字串陣列作為引數的函式。我想回傳首先按元音數排序然后按字母順序排序的字串陣列。
輸入:['dog', 'cat', 'elephant', 'hippo', 'goat'] 輸出:['cat', 'dog', 'goat', 'hippo', 'elephant']
function vowelMatching(vowels) {
return vowels.match(/[aeiou]/ig) || [];
//The 'i' in regex accounts for capitals
}
function arrangeByVowels(array) {
const outputArray = [];
console.log(array.length)
console.log(outputArray.length)
for(let x=0; array.length === outputArray.length; x ) {
// let x = 0
const filterArray = [];
for(let i =0; i<array.length; i ) {
//console.log(vowelMatching(array[i]).length)
if (vowelMatching(array[i]).length === x) {
filterArray.push(array[i])
}
}
//console.log(filterArray.sort())
outputArray.push(...filterArray.sort())
}
return outputArray
}
console.log(arrangeByVowels(['dog', 'gAg', 'qq', 'cat', 'elephant', 'hippo', 'goat']))
我正在使用嵌套的 for 回圈來實作這一點。x例如,如果我為 example賦值let x = 1并注釋掉外部 for 回圈,它將按字母順序回傳所有帶有 1 個元音的單詞。(這是我追求的結果)
我想回圈x直到array.length === outputArray.length但目前這段代碼回傳一個空陣列,我不知道為什么。
我想我很接近,但不知道我哪里出錯了。我究竟做錯了什么?
uj5u.com熱心網友回復:
作為對您實際問題的后續回答....
問題是您初始 for 回圈中的邏輯
for(let x=0; array.length === outputArray.length; x )
您的條件 array.length === outputArray.length 最初將始終回傳 false,因為您的輸出陣列的長度與初始陣列的長度不同。這將立即結束 for 回圈,因為繼續迭代的條件已失敗。
for 回圈本質上是 while(contition is true) increment x; 你的情況開始是假的。
要更正它,只需更改條件,使其始終為真,直到滿足您的條件:
for(let x=0; outputArray.length < array.length; x )
function vowelMatching(vowels) {
return vowels.match(/[aeiou]/ig) || [];
}
function arrangeByVowels(array) {
const outputArray = [];
for(let x=0; outputArray.length < array.length; x ) { // Logic error was here.
const filterArray = [];
for(let i =0; i<array.length; i ) {
if (vowelMatching(array[i]).length === x) {
filterArray.push(array[i])
}
}
outputArray.push(...filterArray.sort())
}
return outputArray
}
console.log(arrangeByVowels(['dog', 'gAg', 'porcupine', 'qq', 'alligator', 'cat', 'elephant', 'albatross', 'hippo', 'goat', 'potato', 'banana','aardvark' ]))
uj5u.com熱心網友回復:
這可以在單個 .sort() 中完成;
let source = ['dog', 'gAg', 'qq', 'cat', 'elephant', 'hippo', 'goat', 'arose', 'unity', 'arise']
let result = source.sort((a,b) => {
let aVowels = a.match(/[aeiou]/gi) || [];
let bVowels = b.match(/[aeiou]/gi) || [];
return aVowels.length === bVowels.length ?
(a > b ? 1 : -1) : // same number of vowels so compare alphabetically
(aVowels.length > bVowels.length ? 1 : -1) // different number of vowels so compare lengths
})
console.log(result);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/456889.html
標籤:javascript 数组 排序 for循环
上一篇:如何在VBA中進行適當的增量?
