[英]Given campgrounds array, write a function that returns a sum and matching input string
I have been given a campgrounds array and I need to write a function, countByView() with 2 parameters, (campgrounds, view).我得到了一个露营地数组,我需要编写一个函数 countByView() 和 2 个参数,(露营地,视图)。 I then need to add up the total number of campgrounds with the same view, and return the matching string value for that input.然后我需要将具有相同视图的露营地总数相加,并返回该输入的匹配字符串值。
For example: countByView(campgrounds, 'ocean') //-> 3
例如: countByView(campgrounds, 'ocean') //-> 3
Here is the given array:这是给定的数组:
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 }
];
Here is what I have so far:这是我到目前为止所拥有的:
function countByView(campgrounds, view) {
let ocean = 0;
let forest = 0;
let desert = 0;
for (let i = 0; i < campgrounds.length; i++) {
if (campgrounds.view === 'ocean') {
ocean++;
} else if (campgrounds.view === 'forest') {
forest++;
} else {
desert++;
}
}
}
I'm not sure if I'm calling the campgrounds.view wrong or it's my counter, or everything我不确定是我打电话给 campgrounds.view 错了还是我的柜台,或者其他一切
You only need to count the elements with the passed view
.您只需要使用传递的view
计算元素。 Here is a working version:这是一个工作版本:
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 } ]; function countByView(campgrounds, view) { let total = 0; for (let i = 0; i < campgrounds.length; i++) { if (campgrounds[i].view === view) { total++; } } return total; } console.log(countByView(campgrounds, 'ocean'));
You can also use .filter
to count the matching items:您还可以使用.filter
来计算匹配项:
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 } ]; function countByView(campgrounds, view) { return campgrounds.filter(campground => campground.view===view).length; } console.log(countByView(campgrounds, 'ocean'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.