下面,您可以看到这两个日志的输出。第一行代码清楚地显示了我试图访问的属性的完整对象,但在下一行代码中,我无法使用配置访问它。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);
这就是这些行在控制台中打印的内容
当前回答
console.log(anObject)的输出是误导性的;通过单击>展开控制台中显示的对象树,显示的对象的状态才会解析。当你console.log对象时,它不是对象的状态。
相反,尝试console.log(object .keys(config)),甚至console.log(JSON.stringify(config)),您将看到调用console.log时的键或对象的状态。
您将(通常)发现在console.log调用之后添加了键。
其他回答
我没有得到MongoDB错误消息在抛出错误在我的NodeJS API响应,所以我做了以下工作
// It was not working
console.log(error.message) // prints the error
let response = error;
// message property was not available in the response.
/*
{
"status": "error",
"error": {
"driver": true,
"name": "MongoError",
"index": 0,
"code": 11000,
"keyPattern": {
"event_name": 1
},
"keyValue": {
"event_name": "followup"
}
}
}
*/
// so I did this
let message = error.message;
let response = JSON.parse(JSON.stringify(error));
response.message = message;
// message property is now available in the response.
/*
{
"status": "error",
"error": {
"driver": true,
"name": "MongoError",
"index": 0,
"code": 11000,
"keyPattern": {
"event_name": 1
},
"keyValue": {
"event_name": "followup"
},
"message": "E11000 duplicate key error collection: mycollections.notificationevents index: event_name_1 dup key: { event_name: \"followup\" }"
}
}
*/
console.log(anObject)的输出是误导性的;通过单击>展开控制台中显示的对象树,显示的对象的状态才会解析。当你console.log对象时,它不是对象的状态。
相反,尝试console.log(object .keys(config)),甚至console.log(JSON.stringify(config)),您将看到调用console.log时的键或对象的状态。
您将(通常)发现在console.log调用之后添加了键。
在我的情况下,我将一个对象传递给一个承诺,在承诺中,我向对象添加了更多的键/值,当它完成时,承诺返回对象。
然而,我稍微多看了一下,承诺是在完全完成之前归还对象……因此,我的其余代码试图处理更新的对象,而数据还没有出现。但就像上面一样,在控制台中,我看到对象完全更新,但无法访问键-它们返回时未定义。直到我看到了这个:
console.log(obj) ;
console.log(obj.newKey1) ;
// returned in console
> Object { origKey1: "blah", origKey2: "blah blah"} [i]
origKey1: "blah"
origKey2: "blah blah"
newKey1: "this info"
newKey2: "that info"
newKey3: " more info"
> *undefined*
[i]是一个小图标,当我悬停在它上面时,它说左边的对象值在记录时被快照,下面的值刚刚被评估。这时我突然想到,我的对象在承诺完全更新之前就已经被评估了。
我今天在React中遇到了类似的问题。最终意识到问题是由尚未确定的状态引起的。我正在调用user.user.name,尽管它显示在控制台中,但我似乎无法在我的组件中访问它,直到我包含了一个检查来检查是否user.name。设置用户,然后调用User . User .name。
我遇到过这样的问题,发现解决方案与Underscore.js有关。我最初的日志记录毫无意义:
console.log(JSON.stringify(obj, null, 2));
> {
> "code": "foo"
> }
console.log(obj.code);
> undefined
我还通过查看对象的键找到了解决方案:
console.log(JSON.stringify(Object.keys(obj)));
> ["_wrapped","_chain"]
这让我意识到obj实际上是一个围绕对象的Underscore.js包装器,最初的调试对我撒谎了。