下面,您可以看到这两个日志的输出。第一行代码清楚地显示了我试图访问的属性的完整对象,但在下一行代码中,我无法使用配置访问它。Col_id_3(见截图中的“undefined”?)有人能解释一下吗?我也可以访问除field_id_4之外的所有其他属性。
console.log(config);
console.log(config.col_id_3);
这就是这些行在控制台中打印的内容
下面,您可以看到这两个日志的输出。第一行代码清楚地显示了我试图访问的属性的完整对象,但在下一行代码中,我无法使用配置访问它。Col_id_3(见截图中的“undefined”?)有人能解释一下吗?我也可以访问除field_id_4之外的所有其他属性。
console.log(config);
console.log(config.col_id_3);
这就是这些行在控制台中打印的内容
当前回答
我的数据只是json数据字符串。(这个变量在会话中存储为json字符串)。
console.log(json_string_object)
->只返回该字符串的表示形式,无法区分是string还是object。
所以为了让它工作,我只需要把它转换回真实对象:
object = JSON.parse(json_string_object);
其他回答
我刚刚从MongoDB使用Mongoose加载文档时遇到了同样的问题。
原来,我使用属性find()只返回一个对象,所以我把find()改为findOne(),一切都为我工作。
解决方案(如果您正在使用Mongoose):确保只返回一个对象,这样您就可以解析它的对象。Id或者它将被视为数组所以你需要像访问对象[0]。Id那样访问它。
我也遇到了这个问题,长话短说,我的API返回的是字符串类型,而不是JSON。所以当你把它打印到日志中时,它看起来完全一样,但是每当我试图访问属性时,它给了我一个未定义的错误。
火守则:
var response = JsonConvert.DeserializeObject<StatusResult>(string Of object);
return Json(response);
之前我刚回来
return Json(string Of object);
您试图访问的属性可能还不存在。Console.log可以工作,因为它在一小段延迟后执行,但其余代码并非如此。试试这个:
var a = config.col_id_3; //undefined
setTimeout(function()
{
var a = config.col_id_3; //voila!
}, 100);
我也遇到了同样的问题,但上面的解决方案对我来说都不奏效,之后我感觉就像是在猜测。但是,在setTimeout函数中包装创建对象的代码对我来说是有用的。
setTimeout(function() {
var myObj = xyz; //some code for creation of complex object like above
console.log(myObj); // this works
console.log(myObj.propertyName); // this works too
});
我也遇到过类似的问题(在为SugarCRM开发游戏时),我的出发点是:
var leadBean = app.data.createBean('Leads', {id: this.model.attributes.parent_id});
// This should load object with attributes
leadBean.fetch();
// Here were my attributes filled in with proper values including name
console.log(leadBean);
// Printed "undefined"
console.log(leadBean.attributes.name);
问题是在fetch(),它的异步调用,所以我必须重写我的代码:
var leadBean = app.data.createBean('Leads', {id: this.model.attributes.parent_id});
// This should load object with attributes
leadBean.fetch({
success: function (lead) {
// Printed my value correctly
console.log(lead.attributes.name);
}
});