控制台报Unexpected Identifier错误,JavaScript代码无法运行求排查
Hey there! Let's break down why you're hitting that "Unexpected Identifier" error and get your code running smoothly.
The Root Cause
The error comes from a misplaced curly brace that breaks the if/else logic in your forEach callback. Here's where it goes wrong:
if (movie.havewatched) result += "watched" ; }else {
You closed the curly brace right after the if statement's code, which means the else clause no longer has a matching if to attach to. JavaScript sees this as invalid syntax, hence the "Unexpected Identifier" error.
Additional Small Tweaks
While we're at it, there's a tiny string formatting issue: your "You have" string is missing a trailing space, which would result in awkward output like "You havewatchedWolf of wall street..." instead of "You have watched Wolf of wall street...".
Corrected Code
Here's the fixed version with proper curly brace placement and the spacing fix:
var movies = [ {title : "Wolf of wall street", stars : 5, havewatched : false}, {title : "Mad max fury road", stars : 5, havewatched : true}, {title : "search party", stars : 5, havewatched : false}, {title : "brooklyn nine nine", stars : 5, havewatched : true} ]; movies.forEach(function(movie) { var result = "You have "; if (movie.havewatched) { result += "watched "; } else { result += "not watched "; } result += movie.title + " - " + movie.stars; console.log(result); });
What Changed?
- Moved the closing curly brace of the
ifblock to come after theelseclause is fully defined, so JavaScript recognizes theif/elseas a single logical unit. - Added spaces in the string literals to make the output readable (e.g.,
"You have "instead of"You have"). - Formatted the code with line breaks and indentation for better readability (this doesn't affect functionality but makes debugging way easier!).
When you run this corrected code, you'll see clean output like:
You have not watched Wolf of wall street - 5 You have watched Mad max fury road - 5 You have not watched search party - 5 You have watched brooklyn nine nine - 5
内容的提问来源于stack exchange,提问作者Suhail Mahey

