簡體   English   中英

添加到JS對象或增加密鑰(如果存在密鑰)

[英]Add to JS object or increase count if key exists

我正在嘗試將密鑰添加到對象(如果不存在),或者增加其計數(如果已經存在)。 如果新密鑰不存在,以下代碼將正確添加新密鑰,但如果已經存在,則不會增加其數量。 而是返回{UniqueResult1:NaN, UniqueResult2:NaN}

let detectionHash = {};
    function onDetected(result) {
        detectionHash[result.code]++;
        if(detectionHash[result.code] >= 5) {
          //here's where I want to be
        }
    }

如果密鑰已經存在,如何增加密鑰的數量?

您可以將值或默認值零加一。

不存在的屬性返回undefined ,它是falsy 以下邏輯或|| 檢查此值,並取下一個零值進行遞增。

detectionHash[result.code] = (detectionHash[result.code] || 0) + 1;

如果您請求一個不存在的密鑰,它將是“未定義”類型的:

var abc=[];
abc[5] = 'hi';
console.log(typeof abc[3]); //it will be "undefined", as a string (in quotes)

所以:

let detectionHash = {};
    function onDetected(result) {
        //does the key exists?
        if (typeof detectionHash[result.code] !== "undefined") 
            detectionHash[result.code]++; //exist. increment
        else
            detectionHash[result.code]=0; //doesn't exist. create
        if(detectionHash[result.code] >= 5) {
          //here's where I want to be
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM