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;
}
添加回答
舉報