You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多条件过滤营地数据集函数调试求助:添加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:

  1. No check for party size compatibility: Your function doesn't verify if the campsite can actually fit your group. The campsite's partySize needs to be at least as big as your groupSize (since you can't fit 8 people into a campsite that only holds 4!).
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 13:02:34