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 opening 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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...