![](/img/trans.png)
[英]Using jQuery or JavaScript to find multiples and remainder of 2 numbers
[英]finding the multiples of 2 numbers in an array using .forEach() in javascript
我需要使用 .forEach 方法遍歷一個數組,返回所有值,如果任何數字是 3 或 5 的倍數,然后也是 3 和 5,則該數字必須作為字符串返回。 到目前為止我的代碼:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15];
let count = [];
arr.forEach((item) => {
count[item] = item;
if (count[item] % 3 === 0) {
count[item] = "Fizz";
} else if (count[item] % 5 === 0) {
count[item] = "Buzz";
} else if (count[item] % 3 === 0 || count[item] % 5 === 0) {
count[item] = "FizzBuzz";}
return count;});
console.log(count);
我遇到的問題是我無法讓它返回“FizzBuzz”的最終字符串,並且還省略了在控制台中顯示的計數變量的初始化。
我是 JS 的初學者,所以如果你能在適用的地方提供答案的解釋,我將不勝感激。
下面的輸出圖像:
編輯:
我忘了提到這是一個練習,它是作業的一部分,所以我需要使用 forEach 方法,這也使它與其他鏈接的問題不同,因為那里使用了 for 循環。
您需要先檢查“FizBuzz”,然后分別檢查“Fizz”和“Buzz”。 在這種情況下,我更喜歡使用.map而不是.forEach在這種情況下,因為.map返回每個元素,因此您不需要創建新的空數組。
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] const res = arr.map(el => { if(el % 3 === 0 && el % 5 === 0) return "FizBuzz" else if (el % 3 === 0) return "Fizz" else if (el % 5 === 0) return "Buzz" else return el }) console.log(res)
我使用保護子句使整個 if 語句的內容更干凈一些
您可以將 Array.forEach() 與索引一起用作參數,這在這里很有幫助
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; arr.forEach(function(element, index) { if (element % 5 === 0 && element % 3 === 0) return arr[index] = "Fizz-Buzz" if (element % 5 === 0) return arr[index] = "Buzz" if (element % 3 === 0) return arr[index] = "Fizz" }) console.log(arr)
還要注意,javascript arrays 以索引 0 開頭...所以count[item] = [item]
在 count[0] 處留下一個未定義的位置...您應該讓 forEach ZC1C425268E68385D1AB5074C14 使用 index 參數可以傳遞給它(在您的特定情況下,使用 count[item] = [item] 不會產生那么多問題),但最好從一開始就以正確的方式進行
這里沒有保護條款的代碼:
arr.forEach(function (element, index) { if (element % 5 === 0 && element % 3 === 0) { arr[index] = "Fizz-Buzz" } else if (element % 5 === 0) { arr[index] = "Buzz" } else if (element % 3 === 0) { arr[index] = "Fizz" } })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.