首页 > 解决方案 > 这个JS有问题吗?

问题描述

我正在尝试使用 JS 和 p5.js 编写国际象棋游戏代码,但我的代码中有一个问题,我已经有几天无法解决了。

这是代码:

function setup() {
  // some other stuff: init canvas & board, set noStroke()

  let wp1 = new Piece('white', ['a', 2], 'p', board);
  wp1._draw();
}

我在let wp1 = new Piece('white', ['a', 2], 'p', board);. 它来自构造函数。我在那里有很多其他代码,但这是有错误的部分:

  switch (type) { // "type refers to the third argument, 'p', from the code above
      case 'p':
        this.type = new Pawn(this.color, this.square);
      case 'r':
        this.type = new Rook(this.color, this.square);
      case 'n':
        this.type = new Knight(this.color, this.square);
      case 'b':
        this.type = new Bishop(this.color, this.square);
      case 'k':
        this.type = new King(this.color, this.square);
      case 'q':
        this.type = new Queen(this.color, this.square);
      default:
        console.error(`Expected piece type as a one-letter string, but got "${type}".`);
    }

即使我将“p”传递给函数,我仍然在底部收到错误,而且,显然,'p' === 'p'应该没有错误。我尝试了几种不同的方法来解决这个问题。首先,我尝试将代码重写为if语句而不是switch语句,格式如下:

if (type == 'p') {
  this.type = new Pawn(this.color, this.square);
} else if (type == 'r') {
  // same as above but with Rook()
} // ... and as such for all the other piece types
else {
  console.error(`Expected piece type as a one-letter string, but got "${type}".`);
}

...我仍然得到错误!

我尝试将字符串 'p' 替换为所有其他片段类型('r'、'n'、'b'、'q' 和 'k'),但无济于事。

为什么这不起作用?

标签: javascriptstringif-statementswitch-statement

解决方案


每个MDN:

与每个 case 标签关联的可选 break 语句确保程序在执行匹配的语句后跳出 switch,并在 switch 后面的语句处继续执行。如果省略了break,程序将继续执行switch语句中的下一条语句。

如果您break不希望脚本继续执行 switch 语句中的行直到到达console.error.

像这样:

  switch (type) { // "type refers to the third argument, 'p', from the code above
      case 'p':
        this.type = new Pawn(this.color, this.square);
        break;
      case 'r':
        this.type = new Rook(this.color, this.square);
        break;
      case 'n':
        this.type = new Knight(this.color, this.square);
        break;
      case 'b':
        this.type = new Bishop(this.color, this.square);
        break;
      case 'k':
        this.type = new King(this.color, this.square);
        break;
      case 'q':
        this.type = new Queen(this.color, this.square);
        break;
      default:
        console.error(`Expected piece type as a one-letter string, but got "${type}".`);
    }

这是 usingswitch语句的预期模式。


推荐阅读