猿问

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

大家好,有人可以帮我看看我是否遗漏了什么。看来我无法将它们转换为数字。


//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;

}


慕丝7291255
浏览 146回答 3
3回答

白板的微信

如果您实际上只想要露营地数组中的露营地数量,则可以使用:campgrounds.length就像你已经在 for 循环中一样如果出于某种原因您需要增加 for 循环中的计数(也许这是出于学习目的而给您的某种作业,当您在 for 循环初始化程序中使用campgrounds.length 时仍然看起来有点奇怪),您可以每次迭代时增加计数:function campsiteCount(campgrounds) {&nbsp; let counter = 0;&nbsp; for(let i = 0; i < campgrounds.length; i++) {&nbsp; &nbsp; counter++;&nbsp; }&nbsp; return counter;}或者,如果您想总结所有聚会规模,我想这可能就是您想要的?你会这样做:function campsiteCount(campgrounds) {&nbsp; let counter = 0;&nbsp; for(let i = 0; i < campgrounds.length; i++) {&nbsp; &nbsp; counter += campgrounds[i].partySize;&nbsp; }&nbsp; return counter;}

料青山看我应如是

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

慕田峪7331174

//For future reference, this worked:function campsiteCount(campgrounds) {&nbsp; let counter = 0;&nbsp; for(let i = 0; i < campgrounds.length; i++) {&nbsp; &nbsp; counter = campgrounds.length;&nbsp; }&nbsp; return counter;}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答