Mic*_*hał 1 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
}
}
Run Code Online (Sandbox Code Playgroud)
如果密钥已经存在,如何增加密钥的数量?
您可以将值或默认值零加一。
不存在的属性返回undefined,这是虚假的。以下逻辑或||检查该值,并取下一个零值进行递增。
detectionHash[result.code] = (detectionHash[result.code] || 0) + 1;
Run Code Online (Sandbox Code Playgroud)