我正在尝试将解码的 JSON 数组中的一堆元素添加在一起:
var jqXHR = $.getJSON("data.php", function(jsonData) {
newItems = jsonData['New']['count'] || 0;
unsolvedItems = (jsonData['New']['count'] || 0)+
(jsonData['b']['count'] || 0)+
(jsonData['c']['count'] || 0)+
(jsonData['d']['count'] || 0)+
(jsonData['e']['count'] || 0)+
(jsonData['f']['count'] || 0)+
(jsonData['g']['count'] || 0);
}
如您所见,在尝试将值分配给某些内容之前,我尝试使用简写解释 on this site 检查 ['count']
元素是否存在。 ,但是 || 0
速记似乎不起作用。当 JSON 中不包含 ['New']
时,我收到 Uncaught TypeError: Cannot read property 'count' of undefined
。
这对数组不起作用,还是我做错了?如果它不起作用,除了对我想要使用的每个元素使用单独的 if 语句之外,我还能做什么?
最佳答案
问题是,如果 jsonData['d']
为 undefined<,则无法获取
.jsonData['d']['count']
/
你的代码也充满了重复。这种代码维护起来很痛苦。
你可以这样做:
unsolvedItems = 0;
['New','b','c','d','e','f','g'].forEach(function(key){
if (jsonData[key]) unsolvedItems += jsonData[key].count || 0;
});
关于javascript - 检查数组元素是否已定义的简写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23509666/