下面,您可以看到这两个日志的输出。第一行代码清楚地显示了我试图访问的属性的完整对象,但在下一行代码中,我无法使用配置访问它。Col_id_3(见截图中的“undefined”?)有人能解释一下吗?我也可以访问除field_id_4之外的所有其他属性。

console.log(config);
console.log(config.col_id_3);

这就是这些行在控制台中打印的内容


当前回答

我遇到过这样的问题,发现解决方案与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包装器,最初的调试对我撒谎了。

其他回答

我今天也遇到了同样的问题。问题是由uglify-js引起的。在我执行了相同的非丑陋代码后,问题得到了解决。删除的

--mangle-props

从uglify-js中编写丑陋的代码就足够了。

也许,最好的做法是为那些必须被uglify-js的regex规则破坏的属性使用一些前缀。

来源如下:

var data = JSON.parse( content);
...
this.pageIndex = parseInt(data.index);
this.pageTotal = parseInt(data.total);
this.pageLimit = parseInt(data.limit); 

它是这样被丑化的:

var n = JSON.parse( t);
...
this._ = parseInt(n.index), this.g = parseInt(n.total), this.D = parseInt(n.C)

没有一个JSON stringify/parse对我有用。

formValues.myKey:               undefined
formValues.myKey with timeout:  content

我想要formValues的值。myKey是什么技巧是setTimeout 0,就像下面的例子。希望能有所帮助。

console.log('formValues.myKey: ',formValues.myKey);
setTimeout( () => { 
  console.log('formValues.myKey with timeout: ', formValues.myKey);
}, 0 );

如果这是在使用Mongoose时发生的问题,则可能会发生以下情况:

console.log(object)

返回所有内容,包括所需的键。

console.log(object.key)

返回未定义。

如果发生了这种情况,就意味着Mongoose Schema中缺少键。添加它将解决这个问题。

我没有得到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\" }"
  }
}
*/

好吧,我经过了一个让我对新循环感到害怕的情况,感谢我的老派。

forEach循环和for(a in obj)循环都会产生错误的信息和错误,这取决于对象的类型和属性!!

老的好

for(var i=0, max=arr.length; i<max; i++)
{ //Properties available correctly!

   arr[i].property        //both work inside old school loop!
   arr[i][property]  
}