自定义Array.prototype.myEach调用异常及原生forEach失效问题咨询
[1,2,3].myEach() fail when not declaring the array first? Let me break down what's happening here—this is almost certainly a Automatic Semicolon Insertion (ASI) issue, a super common gotcha in JavaScript that trips up even experienced devs.
Here's the core problem: when you write code like this without a semicolon at the end of the line before it:
// Imagine there's code above this that doesn't end with a semicolon [1,2,3,4,5].myEach(function(val, i){ console.log(val); });
JavaScript's parser doesn't see that opening [ as the start of a new array literal. Instead, it thinks you're trying to access a property from the expression that came right before it.
For example, if the line before was something like:
console.log("Testing") [1,2,3].myEach(...)
The parser will twist this into:
console.log("Testing")[1,2,3].myEach(...)
That 1,2,3 uses the comma operator (which just returns the last value, 3), so it's trying to grab the 3rd index of console.log("Testing")'s return value— which is undefined. You can't call .myEach() on undefined, hence the error.
When you declare the array first with let a = [1,2,3];, the semicolon after the declaration tells the parser "this statement is done". So when you call a.myEach(...) next, it's treated as a separate, clean statement with no confusion.
And to be clear: this isn't a problem with your custom myEach method. Even the native forEach would fail in this exact scenario—it's purely a syntax parsing quirk.
Fixes to try:
- Stick to ending statements with semicolons: This is the most reliable way to avoid ASI issues entirely. It's a widely recommended practice for this exact reason.
- Add a leading semicolon if you omit them: If you prefer no semicolons, slap a leading
;before array literals that start a new line:
That leading semicolon acts as a guard, making sure the parser treats the;[1,2,3,4,5].myEach(function(val, i){ console.log(val); });[as the start of a new array, not a property access.
One quick test: if you run just the line [1,2,3,4,5].myEach(function(val, i){ console.log(val); }); in an empty console (no code before it), it should work perfectly. The issue only pops up when there's preceding code missing a trailing semicolon.
内容的提问来源于stack exchange,提问作者TechnoCorner

