You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

控制台报Unexpected Identifier错误,JavaScript代码无法运行求排查

Fixing the "Unexpected Identifier" Error in Your Movie List Code

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 if block to come after the else clause is fully defined, so JavaScript recognizes the if/else as 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 18:52:49