JavaScript数组遍历与对象属性访问作业Step4报错排查求助
Hey Matt, let's break down the issues in your code and fix them step by step. The error you're seeing at Step 4 is actually rooted in a mix of syntax mistakes and misaligned logic with the assignment requirements. Let's work through each problem and correct them:
Key Issues in Your Current Code
- Missing
functionKeyword: You forgot to prefixgetPrices()andgetDiscount()withfunction— this is a critical syntax error that breaks the function definitions entirely, leading to unexpected errors. - Step 4 Misimplementation: Instead of assigning the tax-inclusive price to the
finalPricevariable as required, you’re directly logging the result. The assignment is mandatory before the final log in Step 7. - Duplicate Variable Declaration: You declared
finalPriceboth outside and inside theforloop, causing variable shadowing and violating Step 3’s requirement to declarefinalPriceinside the loop without initializing it first. - Broken
getDiscount()Logic: The condition checks for theguestsparameter are reversed (you’re checking for invalid values instead of valid ones) and usetypeofincorrectly when comparing numeric values. - Unnecessary
try/catch: The assignment doesn’t require exception handling here; defensiveif/elselogic is sufficient for input validation.
Corrected Full Code
// Given variables const dishData = [ { name: "Italian pasta", price: 9.55 }, { name: "Rice with veggies", price: 8.65 }, { name: "Chicken with potatoes", price: 15.55 }, { name: "Vegetarian Pizza", price: 6.45 }, ]; const tax = 1.20; // Implement getPrices() function function getPrices(taxBoolean) { // Fixed: Added function keyword for (let i = 0; i < dishData.length; i++) { // Step 2: Traverse dishData array let finalPrice; // Step 3: Declare finalPrice without initializing it const currentDish = dishData[i]; // Simplify access to current dish object if (taxBoolean === true) { // Step 4: Check if tax should be applied finalPrice = currentDish.price * tax; // Assign tax-inclusive price to finalPrice } else if (taxBoolean === false) { // Step 5: Check if tax should be excluded finalPrice = currentDish.price; // Assign original price to finalPrice } else { // Step 6: Handle invalid boolean input console.log("You need to pass a boolean to the getPrices call!"); return; // Exit function immediately } // Step 7: Log dish name and calculated final price console.log(`Dish: ${currentDish.name}, Price: $${finalPrice.toFixed(2)}`); } } // Implement getDiscount() function function getDiscount(taxBoolean, guests) { // Fixed: Added function keyword getPrices(taxBoolean); // Step 9: Call getPrices with the taxBoolean parameter // Step 10: Defensive check for valid guests input if (typeof guests === 'number' && guests > 0 && guests < 30) { let discount = 0; // Step 11: Initialize discount to 0 if (guests < 5) { discount = 5; // 5% discount for groups smaller than 5 } else if (guests >= 5) { discount = 10; // 10% discount for groups of 5 or more } console.log(`Discount is: $${discount}`); } else { // Step 12: Handle invalid guests input console.log('The second argument must be a number between 0 and 30'); } } // Test calls as specified getDiscount(true, 2); getDiscount(false, 10); // Additional test cases for edge cases getDiscount('invalid-boolean', 5); getDiscount(true, 35);
Key Fixes Explained
- Syntax Correction: Added the
functionkeyword to both function declarations to fix the core error that was triggering your Step 4 issue. - Step 4 Alignment: Now properly assigns the tax-calculated price to
finalPriceinstead of directly logging it, adhering strictly to the assignment’s requirements. - Variable Management: Removed the duplicate
finalPricedeclaration outside the loop and declared it inside without initialization as Step 3 specifies. getDiscount()Logic: Corrected the input validation condition to check for validguestsvalues (number, >0, <30) and fixed the discount calculation by removing incorrecttypeofchecks on numeric values.- Readability: Used
currentDishto simplify accessing the current array element, andtoFixed(2)to ensure prices display with proper currency formatting (2 decimal places).
内容的提问来源于stack exchange,提问作者Matt P
相关产品推荐
相关产品推荐

