遍历List中的每一个元素
List list = [19, 20, 12];
list.forEach((f) => print('$f is ${f > 18 ? 'bigger' : 'smaller'}' + ' than 18'));
打印结果
19 is bigger than 18
20 is bigger than 18
12 is smaller than 18
map方法也是遍历List中的每一个元素。它与forEach的区别在于,map会返回一个新的List对象。
List date = ['09-12', '10-10', '12-25'];
print('date is $date');
List newDate = date.map((f) => '2019-' + f).toList();
print('newDate is $newDate');
打印结果
date is [09-12, 10-10, 12-25]
newDate is [2019-09-12, 2019-10-10, 2019-12-25]
根据传入的函数,给List排序
List nums = [9, 4, 7, 10];
nums.sort((a, b) => a - b);
print('after sort nums is $nums');
// 在unicode编码表中 C在c之前
List strs = ['angela', 'danny', 'ben', 'Catherine'];
strs.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
print(strs);
打印结果
after sort nums is [4, 7, 9, 10]
[angela, ben, Catherine, danny]
依次访问List中所有的元素,并将List中所有的元素根据传入的函数压缩成一个数值。
List list = [1, 2, 3, 4, 5];
var value = list.reduce((a, b) => a * b);
print('value is $value');
var value1 = list.fold(10, (a, b) => a * b);
print('value1 is $value1');
打印结果:
value is 120
value1 is 1200
遍历List中每一个元素,验证是否每一个元素都满足传入函数的要求
List students = ['danny', 'david', 'erik'];
bool startWithD = students.every((s) => s.startsWith('d'));
print('startWithD is $startWithD');
打印结果:
startWithD is false
take从0下标开始,裁剪List到传入下标
skip从传入下标开始,裁剪List到最后一个元素
var fiboNumbers = [1, 2, 3, 5, 8, 13, 21];
var firstTwo = fiboNumbers.take(2);
print('firstTwo is $firstTwo');
var lastTwo = fiboNumbers.skip(5);
print('lastTwo is $lastTwo');
打印结果:
firstTwo is (1, 2)
lastTwo is (13, 21)
返回满足传入函数的集合
List
打印结果:
there are 1 over 21 years old
遍历List中每一个元素,根据传入函数将所遍历元素扩展。将最后所有得出的结果合并为一个新的List。
List list = [1, 2, 3];
var newList1 = list.expand((each) => [each, each + 1]).toList();
print('newList1 is $newList1');
List list1 = [
[1, 2],
[2, 3]
];
var newList2 = list1.expand((each) => each).toList();
print('newList2 is $newList2');
打印结果:
newList1 is [1, 2, 2, 3, 3, 4]
newList2 is [1, 2, 2, 3]