[英]TypeError: Cannot assign to read only property '0' of string
我正在开发终端游戏。 游戏场地被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:无法分配给字符串'░░O░░░░░░O'的只读属性'0'
我想要的示例:
*░░O░░░░░O
░░░░░░░░░░
░░░░O░░░░░
░░░░░░░░░░
░░░O░O░░░░
有很多事情我会解决。
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░░░
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.