[英]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
}
}
如果密鑰已經存在,如何增加密鑰的數量?
如果您請求一個不存在的密鑰,它將是“未定義”類型的:
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.