在Javascript中创建二维数组是否比我在这里有更多功能的方法?也许使用.apply
?
generatePuzzle(size) {
let puzzle = [];
for (let i = 0; i < size; i++) {
puzzle[i] = [];
for (let j = 0; j < size; j++) {
puzzle[i][j] = Math.floor((Math.random() * 200) + 1);
}
}
return puzzle;
}
例如,在python中,您可以执行[[0]*4]*4
之类的操作来创建4x4列表
答案 0 :(得分:4)
const repeat = (fn, n) => Array(n).fill(0).map(fn);
const rand = () => Math.floor((Math.random() * 200) + 1);
const puzzle = n => repeat(() => repeat(rand, n), n);
然后puzzle(3)
,例如,将返回一个填充了随机数的3x3矩阵。
答案 1 :(得分:-1)
用lodash如下:
const _ = require('lodash');
function generatePuzzle(size) {
return _.times(size, () => _.times(size, () => (Math.random() * 200) + 1));
}