挑战:查找乘积
本课属于 Coddy Dart 学习旅程的“基础知识”单元。第 94 课,共 94 课。
挑战
简单在这个挑战中,你将练习遍历列表,找到第一个符合条件的项目。
购物车中有一个产品列表,每个产品都用包含名称、价格和数量的映射表示。你的任务是完成 findProduct 函数,根据产品名称在购物车中搜索产品。
这个函数应返回第一个名称匹配的产品;如果没有找到匹配项,则返回 null。
完成代码,实现正确的搜索功能。
亲手试试
void main() {
// 包含商品的购物车
List<Map<String, dynamic>> shoppingCart = [
{'name': 'Laptop', 'price': 999.99, 'quantity': 1},
{'name': 'Headphones', 'price': 59.99, 'quantity': 2},
{'name': 'Mouse', 'price': 24.99, 'quantity': 1},
{'name': 'Keyboard', 'price': 49.99, 'quantity': 1}
];
// 测试 findProduct 函数
Map<String, dynamic>? foundProduct = findProduct(shoppingCart, 'Headphones');
if (foundProduct != null) {
print('Found: ${foundProduct['name']} - \$${foundProduct['price']} (Quantity: ${foundProduct['quantity']})');
} else {
print('Product not found');
}
// 用不存在的商品进行测试
foundProduct = findProduct(shoppingCart, 'Monitor');
if (foundProduct != null) {
print('Found: ${foundProduct['name']} - \$${foundProduct['price']} (Quantity: ${foundProduct['quantity']})');
} else {
print('Product not found');
}
}
// TODO: 完成这个函数,按名称查找商品
Map<String, dynamic>? findProduct(List<Map<String, dynamic>> cart, String productName) {
// TODO: 遍历购物车,返回第一个与 productName 匹配的商品
// TODO: 如果没有找到匹配的商品,返回 null
}基础知识中的所有课
自己练习: Dart 在线编译器