简体   繁体   English

javascript,意外令牌{

[英]javascript, unexpected token {

Okay, I have a very basic syntax error that I'm having issues resolving. 好的,我有一个非常基本的语法错误,正在解决问题。 Apparently I missed something very basic and important on the code academy class I can't seem to resolve. 显然,我错过了似乎无法解决的代码学院课程中一些非常基础和重要的事情。 I'll post the code below. 我将在下面发布代码。 It should be obvious what I'm trying to do within. 很明显,我在尝试做什么。

The error = "Syntax Error: Unexpected token {" 错误=“语法错误:意外令牌{”

The goal, write my own code incorporating for loops, if/else, and functions. 目标是编写我自己的代码,其中包含for循环,if / else和函数。

var data = ["love", "peace", "anger", "war"]

for (i = 0; i < data.length; i++){
  if (i <=2){
    console.log("life is" + " " +data[i]);
  }
  else if (i <=4){
    console.log("Strife is" + " " + data[i]);
  }
  else (i = 5){
    console.log("That's all for now");
  }
}

The problem, as pointed out, is that else does not take a condition which makes sense as the else body is run when all the other corresponding if/else-if conditionals failed. 这个问题,如所指出的,是else 没有考虑当所有其它相应的if / else,如果条件语句失败其他主体运行这是有意义的条件。

Thus JavaScript (not requiring braces around if/else-bodies) is parsing it as so: 因此,JavaScript(不需要大括号if / else-body)将其解析为:

else Statement

More specifically it starts parsing it as an ExpressionStatement , (i = 5) , followed by an invalid { . 更具体地说,它开始将其解析为ExpressionStatement (i = 5) ,后跟无效的{ It is invalid for the same reason the following is invalid: 由于以下原因无效,它是无效的:

i = 5 { }

Statements must be separated by semicolons - explicitly or via automatic semicolon insertion . 语句必须用分号分隔-显式或自动分号插入 The former is not done and the latter does not apply in the given code. 前者未完成,后者不适用于给定代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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