javascript - 为什么添加分号会使这段代码起作用?

标签 javascript node.js

<分区>

process.on('exit', function () {
    console.log("Exiting normally")
})

process.on('uncaughtException', function (err) {
    console.log("Caught - " + err)
})

[1,2,3,4,5].forEach(function(element) {
    console.log("Loop " + element)
})

这打破了:

Caught - TypeError: Cannot read property 'forEach' of undefined

Exiting normally

而当我添加一个分号时,它起作用了:

process.on('exit', function () {
    console.log("Exiting normally")
})

process.on('uncaughtException', function (err) {
    console.log("Caught - " + err)
}); // Added semi colon here

[1,2,3,4,5].forEach(function(element) {
    console.log("Loop " + element)
})

这是否意味着为了安全起见我应该在每个语句后使用分号?

最佳答案

假设您有一个函数 returnArray(),您猜对了,它会返回一个数组。

假设您调用了这个电话:

#do stuff
returnArray();
[n].blah
#do other stuff
#this returns an array. say [1,2,3,4,5];
#and in the next line it does [n].blah

现在假设你在没有分号的情况下进行相同的调用

#do stuff
returnArray()
[n].blah
#do stuff
#this effectively does [1,2,3,4,5][n]
#which is the nth index element of the returned array.

这类似于获取返回数组的第 n 个索引,这通常不是您想要做的。

关于javascript - 为什么添加分号会使这段代码起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47344333/

相关文章:

javascript - 如何使用 JavaScript 清除浏览历史记录?

node.js - MongoDB insertMany 并跳过重复项

javascript - 没有 'new' 无法调用类构造函数

node.js - 如何运行 eb init 指定 node.js 版本 8?

javascript - 如何从 jQuery 输入中获取值列表

javascript - 在 json_to_sheet 之后使用 XLSX js 对列进行排序和过滤

javascript - d3js 轴日期仅开始和结束值

javascript - javascript 中的正则表达式有问题吗?

node.js - Upstart env 节没有为 Node.js 应用程序设置环境变量(如 NODE_ENV)

node.js - Masonry 在 ES6 中不能与 jQuery 一起使用?