javascript – NodeJS [] .forEach undefined

前端之家收集整理的这篇文章主要介绍了javascript – NodeJS [] .forEach undefined前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我在NodeJS中遇到了[] .forEach的奇怪问题.

(使用NodeJs v5.4.1)

将此代码放在函数

function _buildUserQuestionsForDisplay(question,callback){
    var res = {}
    ["is_open","created","deleted","_id"].forEach(function(v){
        res[v] = question[v]
    })
   ...
   ...
}

抛出错误

[“is_open”,”created”,”deleted”,”_id”].forEach(function(v){

TypeError: Cannot read property ‘forEach’ of undefined

如果我将代码更改为,它可以工作

var arr = ["is_open","_id"];
arr.forEach(function(v){
    res[v] = question[v]
})

我已经在Chrome.console上测试了相同的功能,并且第一种方式正常工作.我知道两者都使用V8 JS引擎,这是一个bug还是我在Javascript规则中缺少的东西?

谢谢!

最佳答案
如果在此行之后没有分号,则代码会中断:

var res = {}

为了最大限度地减少这些问题,如果你不使用它,最好使用一个linter. JSHintESLint都可以作为开发插件添加代码编辑器中(我使用ESLint和SubmlimeText中的Airbnb样式表),也可以使用Gulp或Grunt添加到工作流中,以便在提交代码之前捕获这些错误.

If you choose to omit semicolons where possible,my advice is to insert them immediately before the @R_301_126@ parenthesis or square bracket in any statement that begins with one of those tokens,or any which begins with one of the arithmetic operator tokens “/”,“+”,or “-” if you should happen to write such a statement. – 07002

猜你在找的JavaScript相关文章