我在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规则中缺少的东西?
谢谢!
最佳答案
如果在此行之后没有分号,则代码会中断:
原文链接:https://www.f2er.com/js/429013.htmlvar res = {}
为了最大限度地减少这些问题,如果你不使用它,最好使用一个linter. JSHint
和ESLint
都可以作为开发插件添加到代码编辑器中(我使用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