TypeError 'undefined' 不是 Javascript / Jquery JSON 解析器中的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10455258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:22:34  来源:igfitidea点击:

TypeError 'undefined' is not an object in Javascript / Jquery JSON parser

javascriptjqueryarrays

提问by a_good_swan

Javascript/JQuery noob here, so apologies.

这里是 Javascript/JQuery 菜鸟,很抱歉。

I'm using .ajaxto get a JSON object then the code below to loop through and append the fields to the page. Easy.

我正在使用.ajax获取 JSON 对象,然后使用下面的代码循环遍历并将字段附加到页面。简单。

$.each(data, function(i, item) {
    $("#div-ipos").append(
        "<img src=" + item.user.avatar_small_url + ">&nbsp;"
        + item.user.first_name 
        + "<hr /><br />"
    );
});

It works and the output is as expected, complete with the avatar path passed into an <img>tag.

它工作正常,输出符合预期,完整的化身路径传递到<img>标签中。

However I get the following error:

但是我收到以下错误:

TypeError: 'undefined' is not an object (evaluating 'item.user.avatar_small_url')

类型错误:“未定义”不是对象(正在评估“item.user.avatar_small_url”)

What do I need to do to that variable to make it behave properly in this context?

我需要对该变量做什么才能使其在这种情况下正常运行?

回答by Paul

Use console.log(data);before your $.eachto check what's in it. Most likely the server response contains an extra array element with no user. So the JSON could look like:

console.log(data);在您之前使用$.each以检查其中的内容。服务器响应很可能包含一个没有用户的额外数组元素。因此 JSON 可能如下所示:

[{"user":{"avatar_small_url":"foo","first_name":"bar"}},
 {"user":{"avatar_small_url":"bar","first_name":"foo"}},
 {"something_other_than_user":9000}]

See how the last array element doesn't have a "user". If you have access to the server code, you may want to modify it so there is always a user, or you may modify your Javascript so that it exits early if the user field doesn't exist with something like: if(typeof item.user == 'undefined') return;

看看最后一个数组元素如何没有“用户”。如果您有权访问服务器代码,您可能希望修改它以便始终有一个用户,或者您可以修改您的 Javascript 以便在用户字段不存在时提前退出,例如:if(typeof item.user == 'undefined') return;

回答by Hyman

Sounds like either item.user is not defined, or item is not defined. Have you checked the value of item? I think you are expecting it to be something that it is not.

听起来像 item.user 未定义,或 item 未定义。你检查过物品的价值吗?我认为你期望它成为它不是的东西。

回答by viswa

before fetching check using if condition whether key is present in that array as below

在获取之前使用 if 条件检查该数组中是否存在键,如下所示

if( key in User)
{
    User[key]
}