for (let i = 0; i < response.rows.length; i++) { this.totalMap[i + ''].push(response.rows[i].costBearingCompany); }这样插入报错怎么写
时间: 2024-04-10 09:34:36 浏览: 18
为了解决报错问题,可以尝试使用 `push` 方法之前先确保 `this.totalMap[i + '']` 是一个数组。可以通过以下代码来进行判断和初始化:
```javascript
if (!Array.isArray(this.totalMap[i + ''])) {
this.totalMap[i + ''] = [];
}
this.totalMap[i + ''].push(response.rows[i].costBearingCompany);
```
这样就能确保 `this.totalMap[i + '']` 是一个数组,并且可以成功使用 `push` 方法插入数据。
相关问题
for (let i = 0; i < response.rows.length; i++) { this.totalMap[i + ''].push(response.rows[i].costBearingCompany); }
这段代码是一个 for 循环,用于遍历一个名为 response.rows 的数组。在每次循环中,它将 response.rows[i].costBearingCompany 的值添加到名为 totalMap 的对象中的一个数组中。循环的初始条件是 i 等于 0,循环会一直执行直到 i 不再小于 response.rows.length。每次循环结束后,i 的值会递增。
create_walls(){ const g = []; for(let r = 0; r < this.rows; r ++ ){ g[r] = []; for(let c = 0; c < this.cows; c ++ ){ g[r][c] = false; } } //四周加墙 for(let r = 0; r < this.rows; r ++ ){ g[r][0] = g[r][this.cols - 1] = true; } for(let c = 0; c < this.cols; c ++ ){ g[0][c] = g[this.rows - 1][c] = true; } //随机化 for(let i = 0; i < this.inner_walls_count; i ++){ for (let j = 0; j < 1000; j ++){ let r = parseInt(Math.random() * this.rows); let c = parseInt(Math.random() * this.cols); if(g[r][c] || r == this.rows - 2 && c == 1 || c == this.cols - 2 && r == 1){ continue; } g[r][c] = g[this.rows - 1 - r][this.cols - 1 -c] = true; break; } } const copy_g = JSON.parse(JSON.stringify(g));//深拷贝 if(!this.check_connectivity(copy_g, this.rows - 2, 1, 1, this.cols - 2)){ return false; } for(let r = 0; r < this.rows; r ++ ){ for(let c = 0; c < this.cols; c ++ ){ if(g[r][c]){ this.walls.push(new Wall(r, c, this)); } } } return true; }翻译成Java
以下是将 JavaScript 代码转换为 Java 代码后的结果:
public boolean createWalls() {
boolean[][] g = new boolean[this.rows][this.cols];
for (int r = 0; r < this.rows; r++) {
for (int c = 0; c < this.cols; c++) {
g[r][c] = false;
}
}
// 四周加墙
for (int r = 0; r < this.rows; r++) {
g[r][0] = g[r][this.cols - 1] = true;
}
for (int c = 0; c < this.cols; c++) {
g[0][c] = g[this.rows - 1][c] = true;
}
// 随机化
for (int i = 0; i < this.inner_walls_count; i++) {
for (int j = 0; j < 1000; j++) {
int r = (int) (Math.random() * this.rows);
int c = (int) (Math.random() * this.cols);
if (g[r][c] || (r == this.rows - 2 && c == 1) || (c == this.cols - 2 && r == 1)) {
continue;
}
g[r][c] = g[this.rows - 1 - r][this.cols - 1 - c] = true;
break;
}
}
boolean[][] copy_g = new boolean[this.rows][this.cols];
for (int r = 0; r < this.rows; r++) {
for (int c = 0; c < this.cols; c++) {
copy_g[r][c] = g[r][c];
}
}
if (!this.checkConnectivity(copy_g, this.rows - 2, 1, 1, this.cols - 2)) {
return false;
}
for (int r = 0; r < this.rows; r++) {
for (int c = 0; c < this.cols; c++) {
if (g[r][c]) {
this.walls.add(new Wall(r, c, this));
}
}
}
return true;
}