如何使用Array.map方法筛选时长≤60的食谱并生成指定格式字符串数组
First, let's clarify why you're seeing true/false in your output: when you insert titles.duration <= 60 directly into the template literal, you're evaluating a boolean condition (is the duration ≤60?) and inserting that boolean result instead of the actual duration value. That's why you get strings like "Crepes (truemin)"—the true comes from the comparison, not the duration number.
Let's cover two common use cases you might be aiming for, and how to implement them correctly:
1. Filter Recipes to Only Include Quick Ones (Duration ≤60)
If you want to generate an array only for recipes that take 60 minutes or less, use .filter() first to narrow down the list, then .map() to format the strings:
const recipes = [ { title: 'Crepes', duration: 60, ingredients: ['butter', 'flour', 'eggs', 'milk', 'salt'], servings: 3 }, { title: 'Scrambled Eggs', duration: 20, ingredients: ['eggs', 'milk', 'salt'], servings: 2 }, { title: 'Vegan Salmon', duration: 60 * 24 * 3, ingredients: ['carrots', 'olive oil', 'nori sheets', 'liquid smoke', 'soy sauce'], servings: 10 }, { title: 'Carot Cake', duration: 120, ingredients: ['carrots', 'flour', 'eggs', 'salt', 'milk', 'sugar'], servings: 10 } ]; const quickRecipes = recipes .filter(recipe => recipe.duration <= 60) // Keep only recipes ≤60min .map(recipe => `${recipe.title} (${recipe.duration}min)`); // Format the string console.log(quickRecipes); // Output: ["Crepes (60min)", "Scrambled Eggs (20min)"]
2. Add a "Quick" Note to Short Recipes (Keep All Recipes)
If you want to keep all recipes in the array but highlight those that are quick (≤60min), use a ternary operator to conditionally add a note:
const titlesWithDuration = recipes.map(recipe => { // Check if duration is quick, then build the string const quickNote = recipe.duration <= 60 ? " - Quick" : ""; return `${recipe.title} (${recipe.duration}min)${quickNote}`; }); console.log(titlesWithDuration); // Output: // [ // "Crepes (60min) - Quick", // "Scrambled Eggs (20min) - Quick", // "Vegan Salmon (259200min)", // "Carot Cake (120min)" // ]
Bonus: Rename Your Parameter for Clarity
A small but helpful tip: your current parameter is named titles, but it represents a single recipe object. Renaming it to recipe makes your code easier to read and understand (as shown in the examples above).
内容的提问来源于stack exchange,提问作者Onizuka92

