为了账号安全,请及时绑定邮箱和手机立即绑定

给定一个露营地数组,返回数组中露营地的总数

给定一个露营地数组,返回数组中露营地的总数

慕丝7291255 2023-07-14 16:20:06
大家好,有人可以帮我看看我是否遗漏了什么。看来我无法将它们转换为数字。//This is the data I have:let campgrounds = [  { number: 1, view: 'ocean', partySize: 8, isReserved: false },  { number: 5, view: 'ocean', partySize: 4, isReserved: false },  { number: 12, view: 'ocean', partySize: 4, isReserved: true },  { number: 18, view: 'forest', partySize: 4, isReserved: false },  { number: 23, view: 'forest', partySize: 4, isReserved: true }];//This is my code so far.function campsiteCount(campgrounds) {  let counter = 0;  for(let i = 0; i < campgrounds.length; i++) {    counter = counter + campgrounds[i];  }  return counter;}
查看完整描述

3 回答

?
白板的微信

TA贡献1883条经验 获得超3个赞

如果您实际上只想要露营地数组中的露营地数量,则可以使用:


campgrounds.length

就像你已经在 for 循环中一样


如果出于某种原因您需要增加 for 循环中的计数(也许这是出于学习目的而给您的某种作业,当您在 for 循环初始化程序中使用campgrounds.length 时仍然看起来有点奇怪),您可以每次迭代时增加计数:


function campsiteCount(campgrounds) {

  let counter = 0;

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

    counter++;

  }

  return counter;

}

或者,如果您想总结所有聚会规模,我想这可能就是您想要的?你会这样做:


function campsiteCount(campgrounds) {

  let counter = 0;

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

    counter += campgrounds[i].partySize;

  }

  return counter;

}


查看完整回答
反对 回复 2023-07-14
?
料青山看我应如是

TA贡献1772条经验 获得超8个赞

console.log(campgrounds.length);

数组有一个.length属性可以告诉您数组中的项目数(您已经在 for 循环中使用了)。


查看完整回答
反对 回复 2023-07-14
?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

//For future reference, this worked:


function campsiteCount(campgrounds) {

  let counter = 0;

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

    counter = campgrounds.length;

  }

  return counter;

}


查看完整回答
反对 回复 2023-07-14
  • 3 回答
  • 0 关注
  • 145 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信