1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
const p = console.log; const getRandom0to9 = () => Math.floor(Math.random() * 10); const nums = (() => { const a = []; // 単純なfor文の代わり [...Array(10)].forEach((_, i) => { a[i] = getRandom0to9(); }); return a; })(); const [numsEven, numsOdd] = (() => { const isEven = (n) => (0 === n % 2); const e = []; const o = []; nums.forEach(n => { // メソッドの持ち主を三項演算子で切り替える (isEven(n) ? e : o).push(n); }); return [e, o]; })(); p({ numsEven, numsOdd }); |
1 |
{ numsEven: [ 2, 0, 2, 8, 4, 4 ], numsOdd: [ 3, 7, 5, 7 ] } |