NodeJS [].forEach 未定义
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","created","deleted","_id"];
arr.forEach(function(v){
res[v] = question[v]
})
我在 Chrome.console
上测试了相同的功能,第一种方法有效。
我知道两者都使用 V8
JS 引擎,这是一个错误还是我' m 缺少 Javascript 条规则?
谢谢!
如果您在这行之后没有分号,您的代码就会中断:
var res = {}
为了尽量减少这些问题,如果您不使用 linter,最好使用 linter。 JSHint
and ESLint
都可以作为开发插件添加到您的代码编辑器中(我在 SubmlimeText 中使用 ESLint 和 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. - blog entry by Michaeljohn Clement 2010
我在 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","created","deleted","_id"];
arr.forEach(function(v){
res[v] = question[v]
})
我在 Chrome.console
上测试了相同的功能,第一种方法有效。
我知道两者都使用 V8
JS 引擎,这是一个错误还是我' m 缺少 Javascript 条规则?
谢谢!
如果您在这行之后没有分号,您的代码就会中断:
var res = {}
为了尽量减少这些问题,如果您不使用 linter,最好使用 linter。 JSHint
and ESLint
都可以作为开发插件添加到您的代码编辑器中(我在 SubmlimeText 中使用 ESLint 和 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. - blog entry by Michaeljohn Clement 2010