无法从if主体访问函数内部声明的变量



我正试图访问一个变量,该变量是我从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标记中。

错误中提到的行相差一,而错误实际上在第88行。在修复了我的if语句之后,它现在可以完美地工作了。

供将来参考:使用的浏览器是Windows 10上的Edge(Chromium(96.0.1054.41版本。

最新更新