【问题标题】:TypeError: Cannot assign to read only property '0' of stringTypeError:无法分配给字符串的只读属性“0”
【发布时间】:2021-08-30 06:33:11
【问题描述】:

我正在开发一款终端游戏。游戏场被fieldCharacters (░) 和holes (O) 占据

该字段是随机生成的,但我还想确保 pathCharacter (*) 始终位于该字段的左上角(由一组数组组成)

为此,我将第一个数组的第一个索引分配给 pathCharacter (*)。见以下代码:

String.prototype.replaceAt = function(index, replacement) {
  return this.substr(0, index) + replacement + this.substr(index + replacement.length);
}

hat = '^';

hole = 'O';

fieldCharacter = '░';

pathCharacter = '*';

class Field {
  constructor(field) {
    this._field = field;
  }

  print() {
    this._field = field.join('\n');
    console.log(this._field.replace(/,/g, ''))
  }

  static generateField(height, width) {
    let finalArray = []
    for (let i = 0; i < height; i++) {
      finalArray.push(fieldCharacter.repeat(width));
    }
    for (let i = 0; i < finalArray.length; i++) {
      let randomHoleX = Math.floor(Math.random() * width);
      let randomHoleY = Math.floor(Math.random() * height);
      finalArray[randomHoleY] = finalArray[randomHoleY].replaceAt(randomHoleX, hole);
    }

    // what I tried to do
    finalArray[0][0] = pathCharacter;
    return finalArray.join('\n').replace(/,/g, '');
  }
}

console.log(Field.generateField(5, 10));

输出内容:TypeError: Cannot assign to read only property '0' of string '░░O░░░░░░O'

我想要的示例:

*░░O░░░░░O
░░░░░░░░░░
░░░░O░░░░░
░░░░░░░░░░
░░░O░O░░░░

【问题讨论】:

    标签: javascript arrays loops typeerror


    【解决方案1】:

    我要解决很多问题。

    • 首先,你真的不应该将自己的方法添加到String.prototype;如果您想要任何形式的可维护性,那么这种方式简直是疯了。
    • 其次,您的 print() 方法不起作用(它指的是隐式全局 field 来修改实例字段 _field)——不过,这并不是说您无论如何都在使用它。
    • 您可能应该使用数组数组而不是字符串,以减少笨拙的操作。
    • Field 不需要类:
    const hat = "^";
    const hole = "O";
    const fieldCharacter = "░";
    const pathCharacter = "*";
    
    function generateField(height, width) {
      const field = [];
      for (let y = 0; y < height; y++) {
        field.push(Array.from(fieldCharacter.repeat(width)));
      }
      for (let y = 0; y < field.length; y++) {
        const randomHoleY = Math.floor(Math.random() * height);
        const randomHoleX = Math.floor(Math.random() * width);
        field[randomHoleY][randomHoleX] = hole;
      }
    
      field[0][0] = pathCharacter;
      return field;
    }
    
    function printField(field) {
      for (let y = 0; y < field.length; y++) {
        console.log(field[y].join(""));
      }
    }
    
    const field = generateField(5, 10);
    printField(field);
    

    这个输出

    *░░░░░░░░░
    ░░O░░░░░░░
    ░░░░O░░░░░
    ░░░░░░░░░░
    O░O░░░O░░░
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多