【问题标题】:Syntax error in JavaScript ClassJavaScript 类中的语法错误
【发布时间】:2017-07-18 04:52:17
【问题描述】:

我正在玩一些东西,这是我到目前为止的代码

class Person {
constructor(sex, name, age) {
    this.sex = sex || (
        for (var i = 0; i < 1; i++) {
            let sexes = ['f', 'm'],
                picker = Math.round(Math.random());
            picker === 1 ? this.sex = sexes[0] : this.sex = sexes[1];
        } );
    this.name = name || (
        let names = ["Jane Doe", "Jon Doe"];
        sex === 'f' ? this.name = names[0] : this.name = names[1]; );
    this.age = age || (
        let rand = Math.floor(Math.random() * (50 - 20 + 1) + 20);
        age = rand; ) ;
} }//end class

我收到以下错误,我不知道该怎么办=\:

/Users/Username/Desktop/code/file.js:23
            for (var i = 0; i < 1; i++) {
            ^^^
SyntaxError: Unexpected token for
    at createScript (vm.js:74:10)
    at Object.runInThisContext (vm.js:116:10)
    at Module._compile (module.js:533:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:575:3

【问题讨论】:

  • 出现错误是因为 || 运算符希望在其右侧有一个布尔表达式,但却找到了 for。因此,如果您试图从 for 循环中获取布尔值,则可以将其替换为函数调用。

标签: javascript class syntax conditional-formatting


【解决方案1】:

正如 cmets 中提到的@Nisarg Shah,代码期望在|| 之后有一个值,而不是执行几行代码。

相反,您可以将这些代码行放入一个函数中并调用它,以便在未提供值时提供默认值。

class Person {
  constructor(sex, name, age) {
    function getRandomSex() {
      for (var i = 0; i < 1; i++) {
        let sexes = ['f', 'm'],
          picker = Math.round(Math.random());
        return picker === 1 ? sexes[0] : sexes[1];
      }
    }

    function getName(sex) {
      let names = ["Jane Doe", "Jon Doe"];
      return sex === 'f' ? names[0] : names[1];
    }

    function getRandomAge() {
      return Math.floor(Math.random() * (50 - 20 + 1) + 20);
    }
    this.sex = sex || getRandomSex();
    this.name = name || getName(this.sex);
    this.age = age || getRandomAge();
  }
} //end class

var me = new Person();
console.log(me);

【讨论】:

  • 另外,感谢您和@Nisarg Shah 澄清 ||操作员的行为。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-26
  • 2011-05-09
  • 2013-04-10
  • 1970-01-01
相关资源
最近更新 更多