多条件过滤营地数据集函数调试求助:添加partySize条件后输出不符合预期
Fixing Your Campsite Filter Function
Hey there! Let's break down what's missing in your current code and get it working exactly like the examples.
Key Issues in Your Original Code
You're really close—just two important pieces are missing:
- No check for party size compatibility: Your function doesn't verify if the campsite can actually fit your group. The campsite's
partySizeneeds to be at least as big as yourgroupSize(since you can't fit 8 people into a campsite that only holds 4!). - No handling for empty results: Right now, your function returns an empty array when there are no matches, but the examples expect a specific error string instead.
Corrected Function
Here's the fixed version with both issues addressed, plus comments to explain each step:
function findMyCampsites(campgrounds, location, groupSize) { var available = []; for (var i = 0; i < campgrounds.length; i++) { const currentCamp = campgrounds[i]; // Check all three required conditions together if ( !currentCamp.isReserved && // Camp is not booked currentCamp.view === location && // Matches the desired view currentCamp.partySize >= groupSize // Can fit your entire group ) { available.push(currentCamp.number); } } // Return the array if we found matches, else return the error message return available.length > 0 ? available : 'Sorry, no campsites with that view are available to host your party'; }
Testing the Examples
Let's verify this works with your sample inputs:
findMyCampsites(campgrounds, 'ocean', 8)→ Only campsite #1 meets all conditions (unreserved, ocean view, fits 8 people), so returns[1]findMyCampsites(campgrounds, 'forest', 4)→ Campsite #18 is unreserved, forest view, and fits 4 people, so returns[18]findMyCampsites(campgrounds, 'forest', 6)→ No forest campsites can fit 6 people, so returns the error string
Bonus: A More Concise ES6 Version
If you're curious about cleaner syntax (great for learning!), you can use array methods like filter and map to simplify the code:
function findMyCampsites(campgrounds, location, groupSize) { const available = campgrounds .filter(camp => !camp.isReserved && camp.view === location && camp.partySize >= groupSize) .map(camp => camp.number); return available.length ? available : 'Sorry, no campsites with that view are available to host your party'; }
filter narrows down the list to only matching campsites, map converts those campsites into just their numbers, and we still check the length to return the right result.
内容的提问来源于stack exchange,提问作者Get_Richie
相关产品推荐
相关产品推荐

