Pij*_*usn 3 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) {
console.log('entity=' + entity)
})
Run Code Online (Sandbox Code Playgroud)
输出如下:
["echo"]
function forEach() { [native code] }
Uncaught TypeError: Cannot read property 'echo' of undefined
loaded entity=echo
Run Code Online (Sandbox Code Playgroud)
为什么会出现此错误?我认为那undefined是this在里面.forEach.调用时为什么不通过.forEach?
分号!
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);
});
Run Code Online (Sandbox Code Playgroud)
问题出在这里:
console.log(['echo'].forEach)
['echo'].forEach(function(entity) {
Run Code Online (Sandbox Code Playgroud)
换行被忽略,它被解析为:
console.log(['echo'].forEach)['echo'].forEach(function(entity) {
Run Code Online (Sandbox Code Playgroud)
console.log()返回undefined,并undefined['echo']引发异常.
所以使用分号并快乐.或者不要和受苦.