JavaScript:why.forEach不';不行?
下面是一段代码:JavaScript:why.forEach不';不行?,javascript,foreach,undefined,Javascript,Foreach,Undefined,下面是一段代码: window.addEventListener('load', function() { ['echo'].forEach(function(entity) { console.log('loaded entity=' + entity) }) }) console.log(['echo']) console.log(['echo'].forEach) ['echo'].forEach(function(entity) { consol
window.addEventListener('load', function() {
['echo'].forEach(function(entity) {
console.log('loaded entity=' + entity)
})
})
console.log(['echo'])
console.log(['echo'].forEach)
['echo'].forEach(function(entity) {
console.log('entity=' + entity)
})
输出如下所示:
["echo"]
function forEach() { [native code] }
Uncaught TypeError: Cannot read property 'echo' of undefined
loaded entity=echo
为什么会发生这种错误?我假设undefined
是this
内部.forEach
。为什么在调用.forEach
?分号时它没有被传递强>
问题在于:
console.log(['echo'].forEach)
['echo'].forEach(function(entity) {
换行符将被忽略,此时它将被解析为:
console.log(['echo'].forEach)['echo'].forEach(function(entity) {
console.log()
返回undefined
,而undefined['echo']
引发异常
所以,用分号表示快乐。或者不去忍受痛苦。。您的脚本将被评估为:
console.log(['echo'].forEach)['echo'].forEach(function(entity) {
console.log('entity=' + entity)
})
由于
console.log
返回undefined
,您会得到一个未捕获的类型错误,因为您无法访问undefined上的echo
属性,Javascript可以在没有分号的情况下工作(将换行视为语句结尾),只要下列行的连接在语法上不正确&解析就没有意义
例如:
var a=1
var b=2
将起作用,因为分号将被添加为var a=1 var b=2
没有意义
因此,它将被视为var a=1;变量b=2
。同样地
console.log(['echo'].forEach)
['echo'].forEach(function(entity) {
console.log('entity=' + entity)
})
全文如下:
console.log(['echo'].forEach)['echo'].forEach(function(entity) {
console.log('entity=' + entity)
})
在这里,console.log(…)
被视为具有属性'echo'
的对象。因此出现了错误。所有浏览器都出现了相同的错误??啊,是的。如果没有分号,JavaScript将继续解析。不要依赖于自动添加分号。这是我第一次因为不添加分号而受苦。这是一个严重的问题。谢谢。我很想听听那些提倡在JS中不使用分号的人,他们现在会怎么说。多亏了这个愚蠢的想法,新的JS开发人员在看到没有分号的代码时,不要使用分号,然后这种情况就发生了。当然,在不使用分号的情况下要遵循一些规则,这些规则可以防止出现此类问题,但首先必须学习这些规则。通常我们学的太晚了。
console.log(['echo'].forEach)['echo'].forEach(function(entity) {
console.log('entity=' + entity)
})