我正在嘗試制作一個更高級的科學計算器。我對如何進行這種型別的計算有疑問。我有一個數字陣列,我想檢查哪些給定的數字可以被 3 整除。
有 X 個可被 3 整除的數:a、b、c” 其中 X 是計數,“a、b、c”是可被 3 整除的數?
const collection = [
{ text: "0", value: 0 },
{ text: "1", value: 1 },
{ text: "2", value: 2 },
{ text: "3", value: 3 },
{ text: "4", value: 4 },
{ text: "5", value: 5 },
{ text: "6", value: 6 },
{ text: "7", value: 7 },
{ text: "8", value: 8 },
{ text: "9", value: 9 },
{ text: "10", value: 10 },
{ text: "11", value: 11 },
{ text: "12", value: 12 },
];
//expected output: "There are 5 divisible numbers by 3: 0, 3, 6, 9, 12"
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
將模運算子與 for 回圈一起使用,表示為%
uj5u.com熱心網友回復:
您可以使用 % 運算子。所以如果 number%3 ==0 意味著它除以
uj5u.com熱心網友回復:
查看剩余 (%)運算子。
使用它,您可以提取所有可被 3 整除的數字:
const divisible = collection.map(x => x.value).filter(x => !(x % 3))
并列印它們:
console.log(`There are ${divisible.length} divisible numbers by 3: ${divisible.join(', ')}`)
// There are 5 divisible numbers by 3: 0, 3, 6, 9, 12
uj5u.com熱心網友回復:
您可以使用filter取模 (%) 運算子,使用方法過濾掉包含可被 3 整除的數字的物件。我也使用map過,來創建一個值陣列,而不是物件。
const collection = [
{ text: "0", value: 0 },
{ text: "1", value: 1 },
{ text: "2", value: 2 },
{ text: "3", value: 3 },
{ text: "4", value: 4 },
{ text: "5", value: 5 },
{ text: "6", value: 6 },
{ text: "7", value: 7 },
{ text: "8", value: 8 },
{ text: "9", value: 9 },
{ text: "10", value: 10 },
{ text: "11", value: 11 },
{ text: "12", value: 12 },
];
let divby3 = collection.filter((x)=>x.value % 3 === 0).map((x)=>x.value)
console.log(`There are ${divby3.length} divisible numbers by 3: ${divby3}`)
uj5u.com熱心網友回復:
我有一個數字陣列,我想檢查哪些給定的數字可以被 3 整除。
你有一個物件陣列,value鍵上有一個數字。
我們可以通過以下方式獲得所需的輸出
filter()只能被 3 整除
filter(c => c.value % 3 === 0)map()只從value密鑰中獲取數字join()用逗號分隔結果
const collection = [{ text: "0", value: 0 }, { text: "1", value: 1 }, { text: "2", value: 2 }, { text: "3", value: 3 }, { text: "4", value: 4 }, { text: "5", value: 5 }, { text: "6", value: 6 }, { text: "7", value: 7 }, { text: "8", value: 8 }, { text: "9", value: 9 }, { text: "10", value: 10 }, { text: "11", value: 11 }, { text: "12", value: 12 }, ];
let res = collection.filter(c => c.value % 3 === 0).map(o => o.value);
console.log(`There are ${res.length} divisible numbers by 3: ${res.join(', ')}`);
結果
There are 5 divisible numbers by 3: 0, 3, 6, 9, 12
如果我們想排除0,我們可以將 te 更改filter()為:
let res = collection.filter(c => c.value > 0 && c.value % 3 === 0).map(o => o.value);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/354078.html
標籤:javascript
