为什么添加一个分号使这个代码工作?
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:无法读取属性'forEach'的undefined
正常退出
而当我添加一个分号,它的工作原理:
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考虑以下方式
process.on('',function (err) {..})[1,2,3,4,5].forEach(function(element) { console.log("Loop " + element) })
恍然大悟process.on()没有任何像[1,2,3,4,5]这是为什么它是未定义的属性