作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想创建一个二维对象数组,然后设置一个元素的属性值。
var maze=new Maze(3);
maze.resetField();
function Maze(size){
this.size=size;
this.xPos=0;
this.yPos=0;
this.field=[];
this.resetField=function(){
this.field=[];
this.xPos=0;
this.yPos=0;
var row;
var newWord;
var newPlace;
for(rowCtr=0;rowCtr<this.size;rowCtr++){
row=[];
for(r=0;r<this.size;r++){
newWord="rowCtr"+rowCtr+"r"+r;
newPlace=Place(newWord);
row[r]=newPlace;
}
this.field.push(row);
}
treasureX=1;
treasureY=1;
this.field[treasureY][treasureX].word="treasure";
}
}
function Place(word){
this.word=word;
this.walls=[];
this.addWall=function(route){
this.walls.add(route);
}
}
当代码到达这一行时:
this.field[treasureY][treasureX].word="treasure";
我收到这个错误:
Uncaught TypeError: Cannot set property 'word' of undefined
但是因为我已经用嵌套的 for
循环初始化了所有数组元素,所以 this.field[treasureY][treasureX]
不应该被定义为Place
的实例?
最佳答案
我建议使用 new
Place
的新实例。
newPlace = new Place(newWord);
// ^^^
关于javascript - "Cannot set property of undefined",即使数组已经初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41376996/
我是一名优秀的程序员,十分优秀!