【问题标题】:SyntaxError: Unexpected token var in my js codeSyntaxError:我的 js 代码中出现意外的令牌变量
【发布时间】:2015-01-08 23:23:57
【问题描述】:
  1. 我正在尝试完成一个小的 js 任务,写了代码,但我是 得到一个 SyntaxError: Unexpected token var 。你们能告诉我其中有什么错误吗?
  2. 修改 StudentReport 类,以便不会将成绩打印到 for-in 循环中的控制台。
  3. 但是,getGPA 在最后一行应该仍然可以正常工作。

function StudentReport() {
    var grade1 = 4;
    var grade2 = 2;
    var grade3 = 1;
    var getGPA = function() {
        return (var grade1 + var grade2 + var grade3) / 3;
    };
}

var myStudentReport = new StudentReport();

for(var x in myStudentReport) {
    if(typeof myStudentReport[x] !== "function") {
        console.log("Muahaha! " + myStudentReport[x]);
    }
}

console.log("Your overall GPA is " + myStudentReport.getGPA());

【问题讨论】:

  • return (var grade1 + var grade2 + var grade3)
  • 太可怕了!!你怎么想的?
  • 如果您查看发生错误的行,您应该自己看到它。错误信息非常贴切。
  • 您的大部分标签都不适用。
  • 我现在已经删除了一些

标签: javascript variables inheritance


【解决方案1】:

在使用变量时不要使用var,只有在第一次定义它时才使用。

 return (var grade1 + var grade2 + var grade3) / 3;
         ^^^          ^^^          ^^^

但您的代码有更多问题,因为您正在检查函数,但您没有对其进行编码。

for(var x in myStudentReport) { <-- why are you looking through the function? 

你想做这样的事情

function StudentReport() {
    var grade1 = 4;
    var grade2 = 2;
    var grade3 = 1;
    this.getGPA = function() {
        return (grade1 + grade2 + grade3) / 3;
    };
}

var myStudentReport = new StudentReport();
console.log(myStudentReport.getGPA());

【讨论】:

    【解决方案2】:

    这里没有任何意义,去掉那里的vars。

    return (var grade1 + var grade2 + var grade3) / 3;
    

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 2017-07-17
      • 1970-01-01
      • 2011-11-21
      • 2017-08-05
      • 2021-03-31
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多