给定行数和列数,写3个函数分别输出如下的二维数组(假设给的行数是5,列数是4):1 2 3 45 6 7 8 9 10 11 1213 14 15 1617 18 19 20 1 6 11 16 2 7 12 173 8 13 184 9 14 195 10 15 201 10 11 20 2 9 12 193 8 13 184 7 14 175 6 15 16这个怎么做啊? (function(window, document) {
let sorts = function(option) {
this._init(option);
};
sorts.prototype._init = function(option) {
this.arrs = option.arr;
this.rows = option.rows;
this.cols = option.cols;
this._create();
};
sorts.prototype._create = function(option) {
let nums = 0;
for (let i = 0; i < this.rows; i++) {
document.write('<br>');
for (let j = 0; j < this.cols; j++) {
if (this.arrs[nums]) {
document.writeln(this.arrs[nums]);
nums++;
}
}
}
};
window.sorts = sorts
})(window, document);
new sorts({
rows: 5,
cols: 4,
arr: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20']
}); 这个类型不能算。
1 回答
已采纳
pardon110
TA贡献1038条经验 获得超227个赞
关键是写出行列之间的关系 如下所示
// 横书 function rowFirst(rows,cols){ n = 1 arr = [] for (i=0; i < rows; i++){ s = '' arr[i] = [] for(j=0;j<cols;j++,n++){ arr[i].push(n) s += n + ' ' } console.log(s+"\n") } return arr; } // lineFirst(5,4) // 竖版 function colsFirst(rows,cols){ arr = [] for (i=0; i < rows; i++){ s = '' arr[i] = [] for(j=0;j<cols;j++){ arr[i].push(i+1+rows*j) s += arr[i][j] + ' ' } console.log(s+"\n") } return arr; } // colsFirst(5,4) // 之走 function reverseFisrt(rows,cols){ arr = [] for (i=0; i < rows; i++){ s = '' arr[i] = [] for(j=0;j<cols;j++){ if(j%2==1){ arr[i].push(rows*(j+1)-i) }else{ arr[i].push(i+1+rows*j) } s += arr[i][j] + ' ' } console.log(s+"\n") } return arr; } console.log(reverseFisrt(5,4))
最后一个函数调用效果图如下
2 9 12 19 3 8 13 18 4 7 14 17 5 6 15 16 [ [ 1, 10, 11, 20 ], [ 2, 9, 12, 19 ], [ 3, 8, 13, 18 ], [ 4, 7, 14, 17 ], [ 5, 6, 15, 16 ] ]
添加回答
举报
0/150
提交
取消