如何使用 jQuery .each() 处理空对象

How to handle empty objects with jQuery .each()?

本文关键字:处理 对象 何使用 jQuery each      更新时间:2023-09-26

我遇到了麻烦,数组中的数组是空的。

得到了两个数组,我将其推送到一个新数组中,因此我可以在新数组中使用jQuery .each()。新数组可以具有不同的状态:

包含空数组:

nextEvent = [[ ], [ ]]

包含两个完整的数组,每个数组包含一个对象:

nextEvent = [[object], [object]]

或者包含一个带有一个对象的完整数组:

nextEvent = [[object], [ ]]
nextEvent = [[ ], [object]]

现在我正在尝试在nextEvent上使用 .each(),以便将现有对象数据附加到元素中。

到目前为止,我得到了一个看起来像这样的函数:

$.each(nextEvent, function(i, n){           
    if (nextFeedingTime || nextShowTime){                       
        var time = n[0].Time.toString();                
        //...
        if (nextFeedingTime && nextShowTime){
            if (n[0].Kategorie === "Fütterung"){
                appendFeeding();                    
            } else {                        
                appendShow();               
            }
        } else if (nextFeedingTime && !nextShowTime){                   
            appendFeeding();
        } else if (!nextFeedingTime && nextShowTime){
            appendShow();
        }
    } else {
        //...
   }    
});

注意:nextFeedingTimenextShowTime是我最初推送到nextEvent的数组

这个函数可以工作,但是一旦一个数组为空,我就会收到n[0] is undefined错误。任何想法如何解决这个问题?

添加以下内容:

if(n[0] !== undefined)
检查

未定义的检查并继续。

更简单的方法,无需检查"未定义"

if(!n[0]){ }