获取值
本课属于 Coddy Dart 学习旅程的“基础知识”单元。第 62 课,共 94 课。
映射的 values 属性会返回映射中所有值组成的可迭代集合。这样你就可以只访问值,而不访问对应的键。
创建一个学生成绩映射:
Map<String, int> scores = {
'Alice': 95,
'Bob': 85,
'Charlie': 90
};获取映射中的所有值:
Iterable<int> studentScores = scores.values;
print('Student scores: $studentScores');运行上述代码后,输出将是:
Student scores: (95, 85, 90)你也可以使用 for-in 循环遍历所有值:
for (int score in scores.values) {
print(score);
}执行上述代码后,输出将是:
95
85
90挑战
入门在这个挑战中,你将练习使用 values 属性获取映射中的所有值。values 属性会返回映射中所有值组成的可迭代集合,类似于 keys 会返回所有键。
补全代码,从 fruitPrices 映射中获取所有值,并将它们存储在 prices 变量中。
预期输出:
(1.99, 0.99, 2.49)亲手试试
void main() {
// 水果及其价格的映射
Map<String, double> fruitPrices = {
'apple': 1.99,
'banana': 0.99,
'orange': 2.49
};
// TODO:从 fruitPrices 映射中获取所有值(价格)
// 并将它们存入 prices 变量
var prices;
// 这会打印所有价格
print(prices);
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
基础知识中的所有课
自己练习: Dart 在线编译器