我想创建2d数组并用元素填充它。在每个子阵列中应该是一个随机数字。
var n = 11; //number of elements in subarray
var listofnumbers = [];
var rows = [];
var cols = [];
var rand;
//fill listofnumbers array by numbers
for(i=0; i<=n-1; i++) {
listofnumbers[i] = n - i;
}
//reverse listofnumbers array
listofnumbers.reverse();
//fill array 'cols' with another arrays
for(k=0; k<=n-1; k++) {
rand = listofnumbers[Math.floor(Math.random()*listofnumbers.length)]; // random digit from listofnumbers array
for(j=0; j<=n-1; j++) {
if(j == rand-1) {
rows[j] = rand-1;
} else {
rows[j] = "*";
}
}
console.log("rowsarr at iteration " + k + ": " + rows);
cols[k] = rows;
console.log("colsarr at iteration " + k + ": " + cols);
}
由于某种原因,输出类似于:
rowsarr at iteration 0: *,*,*,*,*,*,*,7,*,*,*
colsarr at iteration 0: *,*,*,*,*,*,*,7,*,*,*
rowsarr at iteration 1: *,*,*,*,*,*,*,7,*,*,*
colsarr at iteration 1: *,*,*,*,*,*,*,7,*,*,*,*,*,*,*,*,*,*,7,*,*,*
rowsarr at iteration 2: *,*,*,3,*,*,*,*,*,*,*
colsarr at iteration 2: *,*,*,3,*,*,*,*,*,*,*,*,*,*,3,*,*,*,*,*,*,*,*,*,*,3,*,*,*,*,*,*,*
等等,直到n次迭代。
问题1:为什么数组“cols”通过最后生成的“rows”数组填充所有元素?它应该将最后生成的数组“行”推送到最后。
问题2:我怎样才能获得像cols = [[n,n,n,n,n],[n,n,n,n,n],...]这样的二维数组。现在我只有cols = [n,n,n,n,n,n,n,n,n,n,n,n,n]?
目前,我的代码如下所示:https://jsfiddle.net/qqf3fL5L/10/
答案 0 :(得分:0)
<强>解决方案:强>
你应该在第一个循环中声明数组'rows',如下所示:https://jsfiddle.net/qqf3fL5L/12/
for(k=0; k<n; k++) {
var rows = [];
for(j=0; j<n; j++) {
rows[j] = "*";
}
cols[k] = rows;
var rand = listofnumbers[Math.floor(Math.random()*listofnumbers.length)]; // random digit from listofnumbers array
cols[k][rand-1] = rand;
}