添加到JS对象或增加密钥(如果存在密钥)

时间:2018-08-11 19:33:26

标签: javascript increment

我正在尝试将密钥添加到对象(如果不存在),或者增加其计数(如果已经存在)。如果新密钥不存在,以下代码将正确添加新密钥,但如果已经存在,则不会增加其数量。而是返回{UniqueResult1:NaN, UniqueResult2:NaN}

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

如果密钥已经存在,如何增加密钥的数量?

2 个答案:

答案 0 :(得分:5)

您可以将值或默认值零加一。

不存在的属性返回undefined,即falsy。以下logical OR ||检查此值,并取下一个零值进行递增。

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

答案 1 :(得分:0)

如果您要求输入不存在的密钥,则该密钥将为“未定义”类型:

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
        }
    }