首页 > 解决方案 > 在 vuejs 中迭代数组数组

问题描述

在这个 JSON 示例中,是否有一种最简单的方法来遍历数组数组


  "game": {

  "sunk_ships": [
    [
      "PatrolBoat",
      "Destroyer"
    ]
  ]
}

在我的代码中,这是我写的,考虑到以前的问题已经回答

for (let i = 0; i < this.getGamePlayerId.sunk_ships.length; i++) {
          let childArray=parent[i];

          for (let j = 0; j < parent[i].length; j++) {
            var innerValue=parent[i][j]
            console.log(parent[i][j]);

              document
                .getElementById(innerValue)
                .classList.add("shipDestroyed");
          }
        }

谢谢

标签: javascriptarrays

解决方案


JSON 是文本数据交换格式。

您要编写的是嵌套循环,有很多方法可以编写。

const json = `{
    "game": {

        "sunk_ships": [["PatrolBoat", "Destroyer"], ["Frigate", "Carrier"]]
    }
}`;

const o = JSON.parse(json)

o.game.sunk_ships.forEach((ships) => 
                          ships.forEach((ship) => 
                              console.log(ship)))


推荐阅读