JavaScript单词搜索生成器for循环仅添加单个单词问题求助
单词搜索生成器批量添加单词失败的问题修复
问题根源
代码中所有循环使用的i都未通过let/const声明,属于全局变量。当main函数的for循环调用tryPlaceWord时,函数内部的循环会修改全局i的值,回到main的循环时,i已被篡改,导致循环仅执行一次就终止。此外,pos等变量未声明,也会造成全局变量污染。
修复方案
- 为所有循环的计数器变量添加
let声明,确保每个变量属于当前块级作用域。 - 为未声明的局部变量(如
pos)添加let声明。 - 替换
var为const/let,符合现代JavaScript规范,避免变量提升引发的问题。
修改后的完整代码
function placeWord(p, grid) { for (let i = 0; i < p.length; i++) { grid[p[i][0]][p[i][1]] = p[i][2]; } } function tryPlaceWord(word, grid, width, height) { let s = 0; const directions = [[0,1], [1,0], [1,1]]; const choices = [word, word.split("").reverse().join("")]; const selectedWord = choices[Math.floor(Math.random() * 2)]; while (s < 2) { const direction = directions[Math.floor(Math.random() * 3)]; const x = Math.floor(Math.random() * width); const y = Math.floor(Math.random() * height); const ystart = y + selectedWord.length > height ? y - selectedWord.length : y; const xstart = x + selectedWord.length > width ? x - selectedWord.length : x; const positions = []; let valid = true; for (let i = 0; i < selectedWord.length; i++) { if (xstart < 0 || ystart < 0) { valid = false; break; } const xpos = xstart + i * direction[1]; const ypos = ystart + i * direction[0]; const pos = grid[ypos][xpos]; if (pos === "*" || pos === selectedWord[i]) { positions[i] = [ypos, xpos, selectedWord[i]]; } else { valid = false; break; } } if (valid && positions.length === selectedWord.length) { placeWord(positions, grid); console.log(positions); return true; } s += 1; } return false; } function show(grid) { for (let i = 0; i < grid.length; i++) { console.log(grid[i].join(" ")); } } function makeGrid(width, height) { const grid = []; for (let i = 0; i < height; i++) { grid[i] = []; for (let y = 0; y < width; y++) { grid[i][y] = "*"; } } return grid; } function main() { const width = 15; const height = 15; const grid = makeGrid(width, height); const words = ["alexander", "camila", "pedro", "luis", "maria"]; for (let i = 0; i < words.length; i++) { console.log(words[i]); tryPlaceWord(words[i], grid, width, height); } show(grid); } main();
额外优化细节:
- 重命名参数覆盖的
word变量为selectedWord,避免逻辑混淆 - 添加
valid变量简化终止循环的判断逻辑
内容的提问来源于stack exchange,提问作者Alexander Ortiz Cuellar
相关产品推荐
相关产品推荐

