当我使用.map
遍历数组myClasses
且数组中的status
等于'Open'或'In Progress'增量时,我很难加1一个数字乘以1。我的目标是拥有“公开”或“进行中”课程的总数
这是我当前正在做的事情
myClasses.map(a => (a.status === ('Open' || 'In Progress') ? 'Yes' : 'No'))
当前,当一个类是Open或In Progress时,我只输出yes
或no
,但我希望能够向数字变量添加1或0。
这是myClasses数组包含的内容
0: {id: "0000AK", type: "Elective", status: "Open" }
1: {id: "597WUK", type: "Core", status: "Closed" }
2: {id: "082HCE", type: "Core", status: "In Progress"}
3: {id: "091HSN", type: "Elective", status: "Canceled" }
4: {id: "038GAQ", type: "Core", status: "Open" }
现在我的输出看起来像这样Yes,No,Yes,No,Yes
,而不是我希望输出是3
有什么建议吗?
答案 0 :(得分:3)
如果只是计数,您可以简单地使用filter
并获取返回的数组的length
const myClasses = [{id:"0000AK",type:"Elective",status:"Open"},{id:"597WUK",type:"Core",status:"Closed"},{id:"082HCE",type:"Core",status:"In Progress"},{id:"091HSN",type:"Elective",status:"Canceled"},{id:"038GAQ",type:"Core",status:"Open"}];
const count = myClasses.filter(a => a.status === 'Open' || a.status === 'In Progress').length
console.log(count)
答案 1 :(得分:2)
您可以将计数纳入三元组的真实部分。
var myClasses = [{ id: "0000AK", type: "Elective", status: "Open" }, { id: "597WUK", type: "Core", status: "Closed" }, { id: "082HCE", type: "Core", status: "In Progress" }, { id: "091HSN", type: "Elective", status: "Canceled" }, { id: "038GAQ", type: "Core", status: "Open" }],
count = 0,
result = myClasses.map(({ status }) => status === 'Open' || status === 'In Progress'
? (count++, 'Yes')
: 'No'
);
console.log(count);
console.log(result);
要获得计数,您可以减少数组。如果您想检查更多的值,可以使用数组或Set
并检查数据结构是否包含元素。
var myClasses = [{ id: "0000AK", type: "Elective", status: "Open" }, { id: "597WUK", type: "Core", status: "Closed" }, { id: "082HCE", type: "Core", status: "In Progress" }, { id: "091HSN", type: "Elective", status: "Canceled" }, { id: "038GAQ", type: "Core", status: "Open" }],
wanted = ['Open', 'In Progress'],
count = myClasses.reduce((c, { status }) => c + wanted.includes(status), 0);
console.log(count);
答案 2 :(得分:1)
那又如何呢?数组减少
const data = [
{ id: '0000AK', type: 'Elective', status: 'Open' },
{ id: '597WUK', type: 'Core', status: 'Closed' },
{ id: '082HCE', type: 'Core', status: 'In Progress' },
{ id: '091HSN', type: 'Elective', status: 'Canceled' },
{ id: '038GAQ', type: 'Core', status: 'Open' }
];
const res = data.reduce((acc, cur) => {
const status = cur.status;
if (status === 'Open' || status === 'In Progress') {
return acc + 1;
}
return acc;
}, 0);
console.log(res);
答案 3 :(得分:0)
我建议您使用reduce()
而不是map()
:
var count = myClasses.reduce((accumulator, item) => {
if (item.status == 'Open' || item.status == 'In Progress') {
return accumulator + 1;
}
return accumulator;
}, 0);
请注意,我还如何修改if
语句中的条件以与所需的两个值进行比较。