首页 > 解决方案 > How to load a multidimensional array using for loop in JS?

问题描述

[just joined. first post \o/]

I'm working on a 'battleblocks' project idea of mine to help learn JS, where I have a 10x10 css grid of dynamically created divs. They are identifiable from numbers 1 to 100, reading left to right (row 1 has 1,2,3..10, row 2 has 11,12..20 etc). I need to be able to have a nested array of columns that house 10x arrays (columnArray[0] contains 1,11,21..91 - columnArray[1] contains 2,12,22..92 etc). And the same for rows - a row array that has 10x row arrays (rowArray[0] contains 1,2,3..10 - rowArray[1] contains 11,12,13..20 etc).

Ive declared column array globally, but as it stands whatever ive done so far causes a 'aw, snap! something went wrong while displaying this webpage.' error.

loadColsArray();


// load column arrays
function loadColsArray() {
  let rowsAr = [];
  let count = 0;
  for (let c = 1; c <= 10; c++) {

    for (let r = 0; r <= 100; r + 10) {
      rowsAr[count] = c + r;
      count++;
    }

    columnArray[c - 1] = rowsAr;
    count = 0;
    rowsAr = [];
  }
  console.log(columnArray);
}

Any help appreciated.

ps: added code as a snippet, because 'code sample' option broke up my pasted code.

标签: javascriptarraysnested

解决方案


There are a few problems in your code:

  • The "Aw Snap" is caused by an infinite loop in your code which occurs because you never increment r. You must use r += 10 to increment it by 10.

  • Since you initialise r to 0, your exit condition must be r < 100, otherwise 11 iterations will occur.

  • You also need to define columnArray before you use it (it's not defined in the snippet).

Try this:

let columnArray = [];                       // ←

loadColsArray();

// load column arrays
function loadColsArray() {
  let rowsAr = [];
  let count = 0;
  for (let c = 1; c <= 10; c++) {

    for (let r = 0; r < 100; r += 10) {     // ←
      rowsAr[count] = c + r;
      count++;
    }

    columnArray[c - 1] = rowsAr;
    count = 0;
    rowsAr = [];
  }
  console.log(columnArray);
}


推荐阅读