Dart List

List 使い方

Dart List チートシート

every

Listの全てのエレメントが条件を満たすかチェック。返り値はbool

1
final allEven = items.every((item) => item % 2 == 0);
1
const allEven = items.every(item => item % 2 == 0);

map

すべての要素に対して与えられた関数を呼び出し、その結果からなる新しい配列を生成

1
final newItems = items.map((item) => item + 1).toList();
1
const newItems = items.map(item => item + 1);

fold

すべての要素に対して与えれた関数を呼び出し、単一の値にして返す

初期値を指定する順番が、JavascriptとDartでは異なる

1
2
3
4
final totalPrices = items.fold(0, (total, current) {
total = total + current.price;
return total;
});
1
2
3
4
const totalPrices = items.reduce((total, current) => {
total = total + current.price;
return total;
}, 0);

add

配列の末尾に要素を追加。Javascriptは新しい配列の長さを返すが、Dartはvoidを返す

1
items.add(42);
1
items.push(42);

contains

特定の要素が配列に含まれているかどうかチェック。返り値はbool

1
final includes = items.contains(42);
1
const includes = items.includes(42);

コメント

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×