forEach map filter reduce

map

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

filter

 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

 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

参考

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


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

Last-modified: 2018-08-31 (金) 06:18:35