* forEach map filter reduce [#kb95b49a]


** map [#qe059aa5]

 let nums = [ 1, 2, 3, 4 ];
 let ret = nums.map((n) => { return n * 2; });
 console.log(ret);
 
  => [ 2, 4, 6, 8 ]

** filter [#f04fb4a7]

 let nums = [ 1, 2, 3, 4 ];
 let ret = nums.filter((n) => { return n % 2 === 0 ? true : false; });
 console.log(ret);
 
  => [ 2, 4 ]

 let nums = [ 1, 2, 3, 4 ];
 let ret = nums.filter((n) => { return true; });
 console.log(ret);
 
  => [ 1, 2, 3, 4 ]

 let nums = [ 1, 2, 3, 4 ];
 let ret = nums.filter((n) => { return false; });
 console.log(ret);
 
  => []

** reduce [#r8169995]

 let total = [0, 1, 2, 3].reduce((sum, value) => sum + value);
 console.log(total);
 
  => 6 // = 0 + 1 + 2 + 3

 let total = [0, 1, 2, 3].reduce((sum, value) => sum + value, 100);
 console.log(total);
 
  => 106 // = 100 + 0 + 1 + 2 + 3

 let result = ['A', 'B', 'C'].reduce((str, value) => str + value);
 console.log(result);
 
  => ABC

 let result = ['A', 'B', 'C'].reduce((str, value) => str + value, 'X');
 console.log(result);
 
  => XABC

*** 参考 [#r4b9996a]

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce



トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS