[英]JavaScript: why .forEach doesn't work?
Here is a little piece of code: 这是一小段代码:
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)
})
Output looks like this: 输出如下:
["echo"]
function forEach() { [native code] }
Uncaught TypeError: Cannot read property 'echo' of undefined
loaded entity=echo
Why does this error occur? 为什么会出现此错误? I assume that
undefined
is this
inside .forEach
. 我认为
undefined
是this
里面.forEach
。 Why doesn't it get passed when calling .forEach
? 调用
.forEach
时为什么不通过它?
SEMICOLONS! 分号!
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);
});
The problem is here: 问题出在这里:
console.log(['echo'].forEach)
['echo'].forEach(function(entity) {
The line break is ignored, at it gets parsed as this: 换行被忽略,它被解析为:
console.log(['echo'].forEach)['echo'].forEach(function(entity) {
console.log()
returns undefined
, and undefined['echo']
raises an exception. console.log()
返回undefined
, undefined['echo']
引发异常。
So use semicolons and be happy. 所以使用分号并快乐。 Or don't and suffer.
或者不要和受苦。
You need to add semi-colons . 你需要添加分号 。 Your script is being evaluated as:
您的脚本正在评估为:
console.log(['echo'].forEach)['echo'].forEach(function(entity) {
console.log('entity=' + entity)
})
And since console.log
returns undefined
, you get an uncaught TypeError because you can't access an echo
property on undefined
. 并且由于
console.log
返回undefined
,因此您无法访问undefined
的echo
属性,因此会收到未被捕获的TypeError。
Javascript can work without semicolons (treating newlines as end of statement), as long as concatenation of following lines is syntactically incorrect & parsing makes no sense. Javascript可以在没有分号的情况下工作(将换行视为语句的结尾),只要以下行的连接在语法上不正确并且解析没有意义。
For eg: 例如:
var a=1
var b=2
would work since the semicolon will be added as var a=1 var b=2
doesn't make sense. 可以工作,因为分号将被添加为
var a=1 var b=2
没有意义。
Thus it will be treated as var a=1; var b=2
因此它将被视为
var a=1; var b=2
var a=1; var b=2
. var a=1; var b=2
。 Similarly, 同样的,
console.log(['echo'].forEach)
['echo'].forEach(function(entity) {
console.log('entity=' + entity)
})
is read as : 读作:
console.log(['echo'].forEach)['echo'].forEach(function(entity) {
console.log('entity=' + entity)
})
Here console.log(...)
is treated an object with the property 'echo'
. 这里
console.log(...)
被视为具有属性'echo'
的对象。 Hence the error. 因此错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.