gpt4 book ai didi

javascript - 如何在js中创建多个随机数数组?

转载 作者:行者123 更新时间:2023-12-05 03:25:53 24 4
gpt4 key购买 nike

我正在尝试创建一个包含 3 个数组的矩阵,每个数组包含 10 个元素。每个元素应该是 1 到 10 之间的随机数。我想使用一个函数来生成每个数组,并使用了这个:

var array1 = [];
var array2 = [];
var array3 = [];

var tempName;

function fcnArrayGenerate(){
let i = 1;
while (i < 4){
tempName = "array" + i;
let j = 0;
while (j < 10){
tempName.push((Math.floor(Math.random() * 10) + 1));
j++;
}
i++;
}
console.log(array1);
console.log(array2);
console.log(array3);
}

但是,当我运行该函数时,我收到一条错误消息,指出“tempName.push 不是一个函数”。任何有关如何纠正此问题的帮助将不胜感激。谢谢。

最佳答案

您可以使用单个 multidimensional array,而不是对三个不同的数组使用三个变量。存储这三个数组。

let array = [[], [], []];

function fcnArrayGenerate() {
let i = 0;
while (i <= 2) {
let j = 0;
while (j < 10) {
array[i].push(Math.floor(Math.random() * 10) + 1);
j++;
}
i++;
}
}
// call the function
fcnArrayGenerate();
// now print the arrays as tables
console.table(array);
console.table(array[0]);
console.table(array[1]);
console.table(array[2]);

注意:console.table() 允许您以表格形式将数组和对象打印到控制台。

关于javascript - 如何在js中创建多个随机数数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71899562/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com