简体   繁体   English

检查未定义的javascript没有命中

[英]Checking for undefined javascript not hitting

I'm trying to check if something is undefined in javascript (data[index]) and showing an alert if it is. 我正在尝试检查javascript(data [index])中是否未定义内容,并显示警告。 However, it doesn't seem to be hitting. 但是,它似乎没有受到打击。

I've tried: 我试过了:

  if(data[index]){ }

And i've tried: 我试过了:

  if (typeof(jsVar) == 'undefined') { }

However, neither of them seem to work and I get: 但是,它们似乎都不起作用,我得到:

Uncaught ReferenceError: index is not defined 

Full code: 完整代码:

function myAlerts(data)
{
    $("#alertsListMissingPets").empty();
    $.mobile.loading( 'hide', { theme: "b", text: "Loading", textonly: false});
    if(data[index].Name){
    $.each(data, function(index) {
        console.log(data[index].LostDate)
        $("#alertsListMissingPets").append(" <li><a data-lostid='"+ data[index].LostKey + "' data-custom='"+ data[index].AnimalKey + "' href=\"#\">"+ data[index].Name + " <span class=\"ui-li-count\">"+ data[index].Distance + "</span></a></li>");
    });
    $("#alertsListMissingPets").listview('refresh');
    } else {
        function alertDismissed() {
            $.mobile.changePage("#mainpage");
        }
        navigator.notification.alert('No missing pets in your area!', alertDismissed, 'Good News', 'Okay' );
    }
}

Clearly, the error state that index is undefined. 显然, index未定义的错误状态。 Take a look at your code : 看一下你的代码:

if(data[index].Name){ //Check something with index here
$.each(data, function(index) { //Define index here

You can't use index outside the loop... 您不能在循环外使用index ...

As you can see from the error index variable is undefined . 从错误索引中可以看到,变量undefined未定义的 You should be doing the following 您应该执行以下操作

typeof(index) == 'undefined'

or 要么

typeof(index) != 'undefined'

As stated in other answers/comments from the other posters, your use of $.each and the data[index] definition aren't correct. 如其他海报中的其他答案/评论所述,您对$ .each的使用和data [index]定义不正确。 Try this (untested): 试试这个(未试用):

function myAlerts(data)
{
    $("#alertsListMissingPets").empty();
    $.mobile.loading( 'hide', { theme: "b", text: "Loading", textonly: false});
    if(data.length > 0) {
        $.each(data, function(value) { //index isn't needed based on your code
            $("#alertsListMissingPets").append(" <li><a data-lostid='"+ 
                value.LostKey + "' data-custom='"+ 
                value.AnimalKey + "' href=\"#\">"+ value.Name + 
                "<span class=\"ui-li-count\">"+ value.Distance + 
                "</span></a></li>");
        });
        $("#alertsListMissingPets").listview('refresh');
    } else {
        navigator.notification.alert('No missing pets in your area!', alertDismissed, 'Good News', 'Okay' );
    }
}

//moved this out of your else clause for aesthetics
function alertDismissed() {
    $.mobile.changePage("#mainpage");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM