챌린지: 곱 찾기
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 컴파일러