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

TA贡献1772条经验 获得超8个赞
console.log(campgrounds.length);
数组有一个.length
属性可以告诉您数组中的项目数(您已经在 for 循环中使用了)。

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;
}
添加回答
举报