代码之家  ›  专栏  ›  技术社区  ›  ShaAnder

如何使用基于条件的项填充二维数组

  •  1
  • ShaAnder  · 技术社区  · 3 年前

    有点背景

    我正在做一个小型项目,构建一个由各种数字组成的32 x 32阵列,这些数字代表小地图的瓦片。这些瓦片将被可视化表示,以创建一个看似随机的映射生成器,我只是在JS中这样做,以加强我对数组的理解。

    对于其他上下文:我希望在整个数组中使用一些默认值,如保持不变的3 x 3行(空白/可行走),以确保地图的可行走区域。

    问题

    我目前已经使用它来填充基于默认值的数组:

    function createAndFillTwoDArray({
      rows,
      columns,
      defaultValue
    }) {
      return Array.from({
          length: rows
        }, () =>
        Array.from({
          length: columns
        }, () => defaultValue)
      );
    }
    
    const values = createAndFillTwoDArray({
      rows: 32,
      columns: 32,
      defaultValue: "✔️",
    });
    
    // This populates the array into HTML, and should not effect the actual generation
    const tbody = document.querySelector("tbody");
    
    for (let i = 0; i < values.length; i++) {
      const tr = document.createElement("tr");
      const fields = values[i];
    
      for (let j = 0; j < fields.length; j++) {
        const field = fields[j];
        const td = document.createElement("td");
    
        td.textContent = field;
    
        tr.appendChild(td);
      }
    
      tbody.appendChild(tr);
    }

    因此,我们的问题是,我正试图弄清楚如何传入一个函数或对象,使我能够填充每个数组,但不能从createAndFillTwoDArray函数的范围之外引用该数组

    我尝试了几种方法,首先我尝试从箭头函数中删除默认值,并在其中添加if-else循环语句,然后尝试将默认值设置为对象。

    这两种方法都不起作用,从那时起,我尝试在函数内部和数组创建外部创建它,这也不起作用并导致我的实时服务器崩溃,这是意料之中的。

    function createAndFillTwoDArray({
      rows,
      columns
    }) {
      const arr = Array.from({
          length: rows
        }, () =>
        Array.from({
          length: columns
        }, () => {})
      );
      for (let i = 0; i < arr.length; i++) {
        arr.push("✔️");
      }
      return arr;
    }
    
    const values = createAndFillTwoDArray({
      rows: 32,
      columns: 32,
    });
    1 回复  |  直到 3 年前
        1
  •  5
  •   Barmar    3 年前

    如果希望默认值是一个函数而不是单个值,只需在创建函数中调用即可。

    自从 Array.from() 将索引传递给populate函数,我将其传递给create函数。

    function createAndFillTwoDArray({
      rows,
      columns,
      defaultFunc
    }) {
      return Array.from({
          length: rows
        }, (_, row) =>
        Array.from({
          length: columns
        }, (_, col) => defaultFunc(row, col))
      );
    }
    
    const values = createAndFillTwoDArray({
      rows: 32,
      columns: 32,
      defaultFunc: (x, y) => x == y ? "" : "✔️",
    });
    
    // This populates the array into HTML, and should not effect the actual generation
    const tbody = document.querySelector("tbody");
    
    for (let i = 0; i < values.length; i++) {
      const tr = document.createElement("tr");
      const fields = values[i];
    
      for (let j = 0; j < fields.length; j++) {
        const field = fields[j];
        const td = document.createElement("td");
    
        td.textContent = field;
    
        tr.appendChild(td);
      }
    
      tbody.appendChild(tr);
    }
    <table>
      <tbody>
      </tbody>
    </table>