javascript - 检查javascript中的二维矩阵中是否存在字符串?

标签 javascript arrays

我正在尝试在二维数组中查找horizo​​ntalWord 字符串。 VerticalWord 工作正常,但我在使用 Horizo​​ntalWord 字符串时遇到问题。如果您有任何想法,请告诉我。

 let matrix = [
    [0, 'r', 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    ['a', 'p', 'p', 'l', 'e'],
    [0, 0, 0, 0, 0]
]

function isInMatrix(matrix, word) {

  for (let j = 0; j < matrix[0].length; j++) {

    let verticalWord = ''
    let horizontalWord = ''

    for (let i = 0; i < matrix.length; i++) {
      verticalWord += matrix[i][j]
    }

    for (let k = 0; k < matrix[0].length; k++) {
              horizontalWord += matrix[j][k]
    }

    if ((verticalWord.includes(word)) ||
      (verticalWord.split('').reverse().join('').includes(word)) ||
      (horizontalWord.includes(word)) ||
      (horizontalWord.split('').reverse().join('').includes(word))) return true
  }
  return false
}

console.log(isInMatrix(matrix, 'apple'))

最佳答案

你的循环不正确,你只检查矩阵的前 5 行

for (let j = 0; j < matrix[0].length; j++) {

使用(let j = 0; j < matrix.length; j++)

关于javascript - 检查javascript中的二维矩阵中是否存在字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55335953/

相关文章:

javascript - 基于表单 ID 或名称的 FormData

javascript - 如何对 ES6 `Set` 进行排序?

C 二维数组损坏

c++ - 如何根据第一个或第二个中的较大值对数组对进行排序

javascript - 当我单击 Bootstrap 中的下拉菜单时,它会打开然后自动关闭

javascript - react 上下文: Get Data from API and call API whenever some events happens in React Component

javascript - 有没有更短的方法来定义具有可变键的对象结构?

javascript - 如何修复倒计时时钟 JS HTML CSS

Javascript 数组不带引号

arrays - 将 Int 数组转换为逗号分隔的字符串