如何通过检查对象在javascript中是否未定义将其推入数组
如果已定义对象,我希望将其推入数组,否则将推送“0” 我正在将计数对象发送到计数数组中如何通过检查对象在javascript中是否未定义将其推入数组,javascript,arrays,object,undefined,Javascript,Arrays,Object,Undefined,如果已定义对象,我希望将其推入数组,否则将推送“0” 我正在将计数对象发送到计数数组中 var-emptyObj={'cnt':0}; countArr.push(matchCdnCnt!=“未定义”?matchCdnCnt:emptyObj.cnt); countArr.push(matchInvCnt!=“未定义”?matchInvCnt:emptyObj.cnt); countArr.push(mistchinvcnt!=“未定义”?mistchinvcnt:emptyObj.cnt);
var-emptyObj={'cnt':0};
countArr.push(matchCdnCnt!=“未定义”?matchCdnCnt:emptyObj.cnt);
countArr.push(matchInvCnt!=“未定义”?matchInvCnt:emptyObj.cnt);
countArr.push(mistchinvcnt!=“未定义”?mistchinvcnt:emptyObj.cnt);
countArr.push(mistchcdncnt!=“未定义”?mistchcdncnt:emptyObj.cnt);
countArr.push(onHoldInvCnt!=“未定义”?onHoldInvCnt:emptyObj.cnt);
countArr.push(onHoldCdnCnt!=“未定义”?onHoldCdnCnt:emptyObj.cnt);
countArr.push(availgstnInvCnt!=“未定义”?availgstnInvCnt:emptyObj.cnt);
countArr.push(availgstcdncnt!=“未定义”?availgstcdncnt:emptyObj.cnt);
countArr.push(pendingvcnt!=“未定义”?pendingvcnt:emptyObj.cnt);
countArr.push(pendingCdnCnt!=“未定义”?pendingCdnCnt:emptyObj.cnt);
我想推计数对象或0。您可以这样做:
让emptyObj={'cnt':3};
让未定义的j;
让数组=[
emptyObj&&emptyObj.cnt?emptyObj.cnt:0,
undefinedObj?undefinedObj:0
];
console.log(array)
如果(cnt),只需一个条件即可实现这一点如果(cnt)
,请检查下面的代码片段,我将一个对象数组
用于检查将0推入数组
的所有情况,如果cnt
未定义//null
否则它的推送值为cnt
const数组=[];
常量myObjects=[{cnt:3},{cnt:4},{cnt:5},{cnt:undefined},{cnt:''},{cnt:null}];
MyObject.forEach((m)=>{
常数{cnt}=m;
常数pushElement=cnt | | 0;
array.push(pushElement);
});
console.log(数组)代码>我找到了另一个解决方案,如果需要,它将分配计数0。计数变量返回未定义的else cnt值,如下所示
countArr.push(typeof matchCdnCnt!= 'undefined'? matchCdnCnt.cnt: emptyObj.cnt);
countArr.push(typeof matchInvCnt!= 'undefined'? matchInvCnt.cnt: emptyObj.cnt);
在这个结果之后,我不得不做很多事情。'undefined'
和undefined
是不一样的。你可以使用countArr.push(matchCdnCnt | | emptyObj.cnt)
@AZ_u,如果值是其他虚假值呢?啊,错过了,谢谢@prsvr。将不得不使用三元。