简体   繁体   English

JavaScript:为什么.forEach不起作用?

[英]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 . 我认为undefinedthis里面.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()返回undefinedundefined['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 ,因此您无法访问undefinedecho属性,因此会收到未被捕获的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM