Estoy tratando de acceder a una variable, que declaré en la parte superior de la función desde dentro de una declaración if (también en esa misma función). Este es el código que escribí:
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; }Por alguna razón, falla al intentar aumentar, así que intenté crear una versión más simple:
function simple(x: number, y: number): number { let around: number = 0; if (x > y) { around++; } return around; }La versión simple funciona por alguna razón. Sin embargo, según tengo entendido, ambos deberían funcionar bien, ¿verdad? Aquí está el error que obtengo:
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)La línea 89 contiene el siguiente código:
console.log({max: this.max}); No estoy seguro de si esto es importante, pero estoy usando Nuxt 3 y el código está dentro de una etiqueta de script setup .
La línea mencionada en el error está errada por uno y el error en realidad estaba en la línea 88. Después de corregir mi instrucción if, ahora funciona sin problemas.
Para referencia futura: el navegador utilizado fue Edge (Chromium) versión 96.0.1054.41 en Windows 10.