![](/img/trans.png)
[英]I'm using iron:router v1.0.7 but this.render() is “undefined”. I can't see what I'm doing wrong
[英]I need to find how many vowels are in each string of the array using loops. Can't see what I'm doing wrong
因此,對於一項課程任務,我需要遍歷一系列水果,找出一個單詞中有多少元音和輔音。 對於它說我需要使用 for-in、for 循環和 case-switch 或 nested-if 語句的任務。 這是我的代碼:
const fruits = ["Apple", "Orange", "Banana", "Pear", "Peach", "Strawberry", "Cherry", "Acai"]; for (let fruit in fruits) { var vowels = 0; var consonants = 0; for (var i = 0; i < fruit.length; i++) { switch (fruits[fruit][i]) { case "A": case "E": case "I": case "O": case "U": case "a": case "e": case "i": case "o": case "u": vowels = vowels + 1; break; default: consonants = vowels + 1; break; } } } console.log(`Apple has ${vowels} vowels and ${consonants} consonants`);
我是 JS 的新手,我似乎看不出我做錯了什么。
需要注意的一件事是for-in
用於對象,而 as for-each
用於 arrays。雖然看起來您需要為這個特定的位使用特定的函數,但我想我會指出這一點以備將來使用。
您實際上對代碼所做的是將數組中的每個元素設置為 object。例如,每個變量變為:
0:"Apple", 1:"Orange", ...
所以如果我們遍歷,每個fruit
的長度都是 1。
你問題的答案是看看你如何創建你的 for 循環與你如何創建你的 switch case 相比。 你真正想要的不是fruit
的長度,而是fruits[fruit]
的長度,如果這有意義的話。 例如:
for (var i = 0; i < fruits[fruit].length; i++) {
switch (fruits[fruit][i]){
...
}
}
--
我可以看到的另一個問題是您跟蹤常量的方式。 您可能不應該將常量更新為constants = VOWELS +1
。
--
我注意到的最后一件事是你最后的console.log
實際上不會輸出關於蘋果的信息,它實際上會輸出關於fruits
數組中最后一個水果的信息(即Acai
)
一個可能的解決方案是使用正則表達式。
const regex = /([aeiou])/gi;
const fruits = ["Apple", "Orange", "Banana", "Pear", "Peach", "Strawberry", "Cherry", "Acai"];
const map = fruits.reduce((map, fruit) => {
const vowels = fruit.match(regex);
const consonats = fruit.replaceAll(new RegExp(`(${vowels.join("|")})`, "ig"), "");
map[fruit] = { vowels, consonats: consonats.split("") }
return map;
}, {})
console.log({ map });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.