はじめに
pythonでWebアプリ作ってていつも混ざるのでメモ。
JavaScript
フルバージョン
var orig = [{id: '0000', value: 0},
{id: '0001', value: 1},
{id: '0002', value: 2}];
// filter
var filtered = orig.filter( function(el,idx,ary) {
return el.id=='0001';
});
// [{id: '0001', value: 0}]
// map
var mapped = orig.map( function(el,idx,ary) {
return el.value;
});
// [0, 1, 2]
// reduce
var reduced = mapped.reduce( function(hist,el,idx,ary) {
return hist+el;
});
// 3
// 直接書換え
$.each(orig, function(idx,el) {
el.value += 100;
});
// [{id: '0000', value: 100},
// {id: '0001', value: 101},
// {id: '0002', value: 102}]
それぞれ、elは各要素、idxはインデックス、aryは元の配列。
filter, map, reduceのidx、aryは省略可能。
アロー式
// filter
var filtered2 = orig.filter( el => el.id=='0001' );
// map
var mapped2 = orig.map( el => el.value );
// reduce: lambda式
var reduced2 = mapped2.reduce( (hist,el) => hist+el );
// 直接書換え
$.each(orig, (idx,el) => { el.value+100 } );
reduceのhist
は、それまでの計算の実行結果。
Python
lambda式
orig = [{'id': '0000', 'value': 0},
{'id': '0001', 'value': 1},
{'id': '0002', 'value': 2}]
# filter
filtered = filter(lambda el: el['id']=='0001', orig)
# map
mapped = map(lambda el: el['value'], orig)
# reduce
reduced = reduce(lambda hist,el: hist+el, mapped)
内包表現
# filter
filtered2 = [ el for el in orig if el['id']=='0001' ]
# map
mapped2 = [ el['value'] for el in orig ]
その他注意
オブジェクト内へのアクセス方法
- JavaScriptは
object.key
- Pythonは
object['key']
JavaScriptのアロー式について
// 基本形
function(param1, ..., paramN) { statements }
(param1, ..., paramN) => { statements }
// 値をreturnする場合、{}を省略可能。
function(param1, ..., paramN) { return expression; }
(param1, ..., paramN) => { return expression; }
(param1, ..., paramN) => expression
// 引数が1つの場合、()を省略可能。
(param) => { statements }
param => { statements }