给定一个露营地数组、一种字符串形式的视图类型和一个数字形式的聚会规模

我已经迷上 Javascript 几天了。如果我忘记了什么,我需要你的帮助。提前致谢。


这些是说明:


编写一个函数 findMyCampsites。给定一个露营地数组、一种字符串形式的视图类型和一个数字形式的队伍规模,返回一个包含匹配露营地的露营地编号的数组。


当前可用的露营地(isReserved === false),其视图与输入字符串(例如海洋或森林)匹配,可以容纳输入数量或更大的派对规模,


如果没有可用的站点,则返回字符串“抱歉,没有具有该视图的露营地可用于举办您的派对”


function findMyCampsites(campgrounds, string, number) {

  for(let i = 0; i < campgrounds.length; i++) {

    if(

    campgrounds[i].isReserved === false &&

    campgrounds[i].view === string &&

    campgrounds[i].partySize === number

    ) {

      return campgrounds[i].number;

    } else {

      return "Sorry, no campsites with that view are available to host your party";

    }

  }

}


紫衣仙女
浏览 126回答 2
2回答

慕莱坞森

这段代码将完全按照您的要求进行:function findMyCampsites(campgrounds, string, number) {&nbsp; const campsites = [];&nbsp; for(let i = 0; i < campgrounds.length; i++) {&nbsp; &nbsp; if(&nbsp; &nbsp; campgrounds[i].isReserved === false &&&nbsp; &nbsp; campgrounds[i].view === string &&&nbsp; &nbsp; campgrounds[i].partySize >= number&nbsp; &nbsp; ) {&nbsp; &nbsp; &nbsp; campsites.push(campgrounds[i].number);&nbsp; &nbsp; }&nbsp; }&nbsp; if (campsites.length === 0) {&nbsp; &nbsp; return "Sorry, no campsites with that view are available to host your party";&nbsp; } else {&nbsp; &nbsp; return campsites;&nbsp; }}但是,我想强调几件事,首先,您希望使函数参数更具描述性。即,不要调用第二个参数string,可以将其称为类似的名称siteType,而不是第三个参数number,尝试类似的名称requiredSpaces。另外,这个函数返回一个字符串(如果没有找到站点)和一个数组(如果找到站点)有点奇怪。通常,您通常希望该函数仅返回单一类型,但如果这就是简报要求您做的,那就这样吧。在您的编码职业生涯中,有几件事需要您考虑。

眼眸繁星

function findMyCampsites(campgrounds, string, number) {&nbsp; const campsites = [];&nbsp; for(let i = 0; i < campgrounds.length; i++) {&nbsp; &nbsp; if(&nbsp; &nbsp; campgrounds[i].isReserved === false &&&nbsp; &nbsp; campgrounds[i].view === string &&&nbsp; &nbsp; campgrounds[i].partySize >= number&nbsp; &nbsp; ) {&nbsp; &nbsp; &nbsp; campsites.push(campgrounds[i].number);&nbsp; &nbsp; }&nbsp; }&nbsp; return array.length&nbsp; &nbsp;? array&nbsp; &nbsp;: "Sorry, no campsites with that view are available to host your&nbsp;&nbsp; &nbsp; party";}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript