我有一個物件陣列,它具有布林值的屬性和一些整數值的屬性。例如
const arr = [{
_id: "621bb15de2ecadf024da51d3",
draw: false,
pixel: false,
tooltip: 1,
points: 1,
},
{
_id: "621bb15de2ecadf024da51d8",
draw: false,
pixel: true,
tooltip: 0,
points: 1,
},
{
_id: "621bb15de2ecadf024da51da",
draw: false,
pixel: true,
tooltip: 1,
points: 1,
},
{
_id: "621bb15de2ecadf024da51e5",
draw: false,
pixel: true,
tooltip: 0,
points: 1,
},
{
_id: "621bb15de2ecadf024da51f8",
draw: false,
pixel: true,
tooltip: 1,
points: 1,
},
{
_id: "621bb15ee2ecadf024da5222",
draw: false,
pixel: true,
tooltip: 0,
points: 1,
},
{
_id: "621bb15ee2ecadf024da5230",
draw: false,
pixel: true,
tooltip: 1,
points: 1,
},
{
_id: "621bb15fe2ecadf024da52f3",
draw: false,
pixel: false,
tooltip: 1,
points: 1,
},
{
_id: "621bb160e2ecadf024da5375",
draw: false,
pixel: true,
tooltip: 0,
points: 1,
}
]
我正在嘗試實作 and 的總和,tooltip以及它們為真的points計數draw和位置。pixel
const res = arr.reduce(function (
acc,
curr
) {
return {
tooltip: acc.tooltip curr.tooltip,
points:
acc.points
curr.points,
};
});
我得到如下輸出,這對于總和是正確的,
{
points: 9,
tooltip: 5
}
但我也想要計算它的價值draw以及pixel它的價值在哪里。
Expected Result:
{
points: 9,
tooltip: 5,
pixel: 7,
draw: 0
}
uj5u.com熱心網友回復:
只需使用與tooltipand相同的方式point,因為 在 2 個布林值之間使用運算子,這些布林值將被強制轉換為整數
const arr = [ { _id: '621bb15de2ecadf024da51d3', draw: false, pixel: false, tooltip: 1, points: 1, }, { _id: '621bb15de2ecadf024da51d8', draw: false, pixel: true, tooltip: 0, points: 1, }, { _id: '621bb15de2ecadf024da51da', draw: false, pixel: true, tooltip: 1, points: 1, }, { _id: '621bb15de2ecadf024da51e5', draw: false, pixel: true, tooltip: 0, points: 1, }, { _id: '621bb15de2ecadf024da51f8', draw: false, pixel: true, tooltip: 1, points: 1, }, { _id: '621bb15ee2ecadf024da5222', draw: false, pixel: true, tooltip: 0, points: 1, }, { _id: '621bb15ee2ecadf024da5230', draw: false, pixel: true, tooltip: 1, points: 1, }, { _id: '621bb15fe2ecadf024da52f3', draw: false, pixel: false, tooltip: 1, points: 1, }, { _id: '621bb160e2ecadf024da5375', draw: false, pixel: true, tooltip: 0, points: 1, }, ]
const res = arr.reduce(function (acc, curr) {
return {
tooltip: acc.tooltip curr.tooltip,
points: acc.points curr.points,
draw: acc.draw curr.draw,
pixel: acc.pixel curr.pixel,
}
})
console.log(res)
參考
12.8.3 加法運算子( )
uj5u.com熱心網友回復:
你可以試試這個:
let countPixel = 0;
let countDraw = 0;
const res = arr.reduce(function (
acc,
curr
) {
if (curr.pixel == true) {
countPixel ;
}
if (curr.draw == true) {
countDraw ;
}
return {
tooltip: acc.tooltip curr.tooltip,
points: acc.points curr.points,
pixel: countPixel,
draw: countDraw,
};
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/435737.html
標籤:javascript 数组 映射减少
