従来のforより短くかけることを認めざるを得ない
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 27 |
'use strict' /* 引数の配列から偶数の要素に絞った新たな配列を得る */ const p = console.log const a = [-2, -1, 0, 1, 2, 3, 4, 5] p(a) /* for */ const getOnlyEvenArrayByFor = a => { const b = [] let i = 0; for (const n of a) { if (n % 2 == 0) { b[i++] = n } } return b } /* filter */ const getOnlyEvenArrayByFilter = a => { return a.filter(n => n % 2 == 0) } const getOnlyEvenArrayByFilterOneLiner = a => a.filter(n => n % 2 == 0) p(getOnlyEvenArrayByFor(a)) p(getOnlyEvenArrayByFilter(a)) p(getOnlyEvenArrayByFilterOneLiner(a)) |
1 2 3 4 |
[ -2, -1, 0, 1, 2, 3, 4, 5 ] [ -2, 0, 2, 4 ] [ -2, 0, 2, 4 ] [ -2, 0, 2, 4 ] |