2 回答

TA贡献1871条经验 获得超13个赞
您可以使用Array.from
具有长度的对象,并使用第二个参数映射内部数组。
const
getArray = (l, w) => Array.from({ length: l }, (_, i) =>
Array.from({ length: w }, (_, j) => i * w + j));
console.log(getArray(3, 2));
.as-console-wrapper { max-height: 100% !important; top: 0; }

TA贡献1827条经验 获得超8个赞
您的问题陈述与您尝试的代码不匹配。看来您想将一维数组转换为2D数组。您的代码很好。但是问题是,Math.sqrt(A.length);可能返回floati * rows + j并将变为float,而数组没有float索引。只是Math.ceil()用来修复
function create2Darray(A) {
var columns = [];
var rows = Math.ceil(Math.sqrt(A.length));
for (var i = 0; i < rows; i++) {
columns[i] = [];
for (var j = 0; j < rows; j++) {
columns[i][j] = A[i * rows + j];
}
}
return columns;
}
console.log(create2Darray([1,2,3,4,5,6,7,8]))
以下两个解决方案适用于需要长度和宽度的函数。
function array(l,w){
let res = [];
for(let i = 0; i < l;i++){
res[i] = [];
for(let j = 0; j < w; j++){
res[i][j] = (w * i) + j
}
}
return res;
}
console.log(JSON.strigify(array(3,2)))
可以使用嵌套制作衬垫 map()
const array = (l,w) => [...Array(l)].map((x,i) => [...Array(w)].map((x,j) => (i*w) + j))
console.log(JSON.stringify(array(3,2)))
添加回答
举报