如果键存在,则将其添加到JS对象或增加计数

3

我试图在一个对象中添加一个键,如果它不存在,或者如果它已经存在就增加它的计数。下面的代码可以正确地添加新的键,但如果该键已经存在,则不会增加其计数。相反,它返回{UniqueResult1:NaN, UniqueResult2:NaN}

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

如何在键已存在的情况下增加键值的计数?

1
完整的代码以及您如何使用它来获得意外行为 - ashish singh
2个回答

11
你可以取值或默认值0并加1。
一个不存在的属性返回undefined,它是falsy。下面的逻辑或 ||检查这个值并取下一个值0进行递增。
detectionHash[result.code] = (detectionHash[result.code] || 0) + 1;

这不会替换对象键吗?我真正想要的是存储每个唯一键的计数。第二部分(唯一键)我已经想出来了,只是第一部分还没有。 - Michał
不,那只会改变特定键的值。 - J. Pichardo

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

你没有说明在新键中想要什么值。 1 - Damián Pablo González

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接