第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何捕獲數(shù)組中的匹配計(jì)數(shù)值?

如何捕獲數(shù)組中的匹配計(jì)數(shù)值?

一只斗牛犬 2023-06-15 17:23:56
我有一個(gè)x可以具有以下值的數(shù)組:0: {status: "completed", count: 2}1: {status: "pending", count: 3}現(xiàn)在,如果狀態(tài)匹配,pending那么我想捕獲相應(yīng)的值count。我寫了以下代碼:if (x?.length) {PendingCount = x[1].count;completedCount = x[0].count;}這并不總是給出所需的輸出,因?yàn)閜ending狀態(tài)不一定總是在x[0]
查看完整描述

4 回答

?
瀟瀟雨雨

TA貢獻(xiàn)1833條經(jīng)驗(yàn) 獲得超4個(gè)贊

我會(huì)使用 Array.prototype.find 來查找具有待定狀態(tài)的項(xiàng)目,然后獲取其 count 屬性,如下所示:

const?{?count?}?=?x.find(({?status?}?=?{})?=>?status?===?'pending')?||?{}:

如果存在未決狀態(tài),這將為您提供計(jì)數(shù),如果不存在,則為未定義狀態(tài)。我在這里使用了解構(gòu)和默認(rèn)語法,如果您不熟悉它們,請查看我鏈接的文章。


查看完整回答
反對 回復(fù) 2023-06-15
?
森欄

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超5個(gè)贊

您可以使用過濾器,將找到所有具有待處理狀態(tài)的元素


const data = [{

    status: "completed",

    count: 2

  },

  {

    status: "pending",

    count: 3

  }

];


const pending = data.filter(s => s.status === "pending");

console.log(pending.length ? "got pending" : "no pending")

console.log(pending.map(i=>i.count))


查看完整回答
反對 回復(fù) 2023-06-15
?
繁星點(diǎn)點(diǎn)滴滴

TA貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超3個(gè)贊

如果保證只有 1 個(gè)元素帶有 "pending"?status,那么使用Array.prototype.find根據(jù)其屬性值查找元素似乎是合適的status

const pendingCount = [{

? status: "completed",

? count: 2

}, {

? status: "pending",

? count: 3

}].find(el => el.status === "pending").count;


console.dir(`pending count = ${pendingCount}`);

如果數(shù)組中有多個(gè)“待定”項(xiàng)目并且您需要獲取所有項(xiàng)目的總和,那么使用 Array.prototype.filter?(刪除所有非“待定”項(xiàng)目)然后使用Array.prototype 可能最有意義。減少結(jié)果filter以添加counts。

const pendingSum = [{

? ? status: "completed",

? ? count: 2

? }, {

? ? status: "pending",

? ? count: 3

? }, {

? ? status: "pending",

? ? count: 5

? }, {

? ? status: "pending",

? ? count: 5

? }]

? .filter(el => el.status === "pending")

? .reduce((sum, el) => sum += el.count, 0);


console.dir(`sum of pending items count = ${pendingSum}`);



查看完整回答
反對 回復(fù) 2023-06-15
?
蝴蝶刀刀

TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超8個(gè)贊

const array = [

  {status: "completed", count: 2},

  {status: "pending", count: 3}

];


const pending = array.find(s => s.status === "pending");

if (pending) {

   // Do whatever you want.

}


查看完整回答
反對 回復(fù) 2023-06-15
  • 4 回答
  • 0 關(guān)注
  • 171 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號