javascript - 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.
解决方案
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 user += 10
to increment it by10
.Since you initialise
r
to0
, your exit condition must ber < 100
, otherwise11
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);
}
推荐阅读
- tensorflow - 操作已明确分配给 /GPU:1 但可用设备是
- python - 如何在 Pandas DataFrame 行上打印列名?
- c# - C#对tcp套接字通信进行重试
- javascript - 状态改变时在 React JS 中实现过渡效果
- php - 在两个变量段之间添加静态目录。URL 重写 .htaccess
- java - 如何在 Android 中获取首选项?
- javascript - 通过 id 从对象数组中获取属性的最大值
- java - Eclipse java.lang.OutOfMemoryError:Java 堆空间
- javascript - 动态生成的lightslder和lightgallery
- go - 由未知权威 Kubernetes Engine 签署的证书