添加到 JS 对象或如果键存在则增加计数
Add to JS object or increase count if key exists
我正在尝试为不存在的对象添加一个键,或者如果它已经存在则增加它的计数。如果新键不存在,下面的代码会正确添加它,但如果它已经存在,则不会增加它的计数。相反它 returns {UniqueResult1:NaN, UniqueResult2:NaN}
.
let detectionHash = {};
function onDetected(result) {
detectionHash[result.code]++;
if(detectionHash[result.code] >= 5) {
//here's where I want to be
}
}
如果密钥已经存在,我该如何增加它的数量?
您可以取零值或默认值加一。
不存在的 属性 returns 一个 undefined
,即 falsy. The following logical OR ||
检查此值并取下一个零值进行递增。
detectionHash[result.code] = (detectionHash[result.code] || 0) + 1;
如果您要求的密钥不存在,它将是 "undefined" 类型:
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
}
}
我正在尝试为不存在的对象添加一个键,或者如果它已经存在则增加它的计数。如果新键不存在,下面的代码会正确添加它,但如果它已经存在,则不会增加它的计数。相反它 returns {UniqueResult1:NaN, UniqueResult2:NaN}
.
let detectionHash = {};
function onDetected(result) {
detectionHash[result.code]++;
if(detectionHash[result.code] >= 5) {
//here's where I want to be
}
}
如果密钥已经存在,我该如何增加它的数量?
您可以取零值或默认值加一。
不存在的 属性 returns 一个 undefined
,即 falsy. The following logical OR ||
检查此值并取下一个零值进行递增。
detectionHash[result.code] = (detectionHash[result.code] || 0) + 1;
如果您要求的密钥不存在,它将是 "undefined" 类型:
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
}
}