【发布时间】:2022-01-12 13:40:19
【问题描述】:
我正在尝试访问一个变量,该变量是我在 if 语句内部(也在同一个函数中)在函数顶部声明的。 这是我写的代码:
function getAround(x: number, y: number): number {
console.log({x, y});
let around: number = 0;
const max = (props.size - 1);
console.log({around});
// top
if (y > 0 && grid[y - 1][x].bomb) {
console.log({max: this.max});
around++;
}
// top right
if (y < 0 && x > max && grid[y - 1][x + 1].bomb) {
around++;
}
//right
if (x < max && grid[y][x + 1]) {
around++;
}
//bottom right
if (y < max && x < max && grid[y + 1][x + 1]) {
around++;
}
//bottom
if (y < max && grid[y + 1][x]) {
around++;
}
//left bottom
if (y < max && x > 0 && grid[y + 1][x - 1]) {
around++;
}
//left
if (x > 0 && grid[y][x - 1]) {
around++;
}
//top left
if (y > 0 && x > 0 && grid[y - 1][x - 1]) {
around++;
}
return around;
}
由于某种原因,尝试增加时失败,所以我尝试创建一个更简单的版本:
function simple(x: number, y: number): number {
let around: number = 0;
if (x > y) {
around++;
}
return around;
}
简单的版本出于某种原因工作。根据我的理解,这两个都应该可以正常工作,对吧? 这是我得到的错误:
Error while mounting app: TypeError: Cannot read properties of undefined (reading '1')
at getAround (PlayingField.vue:89)
at PlayingField.vue:50
at Array.forEach (<anonymous>)
at PlayingField.vue:50
at Array.forEach (<anonymous>)
at getAllAround (PlayingField.vue:49)
at generateGrid (PlayingField.vue:41)
at setup (PlayingField.vue:45)
at callWithErrorHandling (runtime-core.esm-bundler.js:6708)
at setupStatefulComponent (runtime-core.esm-bundler.js:6317)
第 89 行包含以下代码:
console.log({max: this.max});
我不确定这是否重要,但我使用的是 Nuxt 3,并且代码位于 script setup 标记内。
【问题讨论】:
-
您误解了错误信息,当您尝试读取
grid[n][1]时未定义grid[n]。 -
另外,如果您将来提供错误消息,请告诉我们是哪一行触发了它,或者在这种情况下,您可以向我们提供 Playground 代码的链接。
-
@Teemu 我不太明白。该错误指出 PlayingField.vue 中的第 89 行。那行是这样的:
console.log({max: this.max});. -
我怀疑定位有点偏离。也许是上面那行,你有
grid[y - 1][x]。检查y-1在if之前是什么,当x == 1时grid[y - 1]是否真的存在。 -
是的。好像只掉了一条线。修复了问题,现在可以了,谢谢!
标签: javascript typescript nuxt.js vuejs3 nuxt3