チャレンジ:積を求める
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オンラインコンパイラ