我正在尝试生成随机数并将数字存储在多维数组o中(需要示例帮助)
[ 8, 52, 9, 34, 51, 19 ]
[ 8, 52, 9, 34, 51, 19 ]
[ 8, 52, 9, 34, 51, 19 ]
目前代码生成集合,但3集是相同的。
[ [ 8, 52, 9, 34, 51, 19 ], [ 8, 52, 9, 34, 51, 19 ], [ 8, 52, 9, 34, 51, 19 ] ]
我的代码如下:
var yourNum = {
yP : [3, 5, 8, 9, 12, 14, 17, 19, 21, 23, 26, 27, 29, 31, 32, 33, 34, 35, 36, 37, 38, 39, 41, 42, 43, 44, 45, 46, 48, 50, 51, 52, 53, 54, 55, 57, 59],
numOfResults: [],
yPvalue : [],
generateRandom: function () {
var nRandom = Math.floor(Math.random() * (yourNum.yP.length));
return nRandom;
}
};
var genResults = function (num) {
var count = num;
for (var i = 0; i < count; i++) {
for (var j = 0; j < 6; j++) {
if(yourNum.yPvalue.length < 6) {
yourNum.yPvalue.push(yourNum.yP[yourNum.generateRandom()]);
}
}
yourNum.numOfResults[i] = yourNum.yPvalue;
}
console.log("---------NEW---------");
console.log(yourNum.numOfResults);
};
//var random = Math.floor(Math.random() * (yourNum.yP.length));
//var yPvalue = yourNum.yP[random];
//console.log("Your random number" + " " + random + " " + yPvalue);
genResults(3);
答案 0 :(得分:2)
你需要
yourNum.yPvalue = [];
后
yourNum.numOfResults[i] = yourNum.yPvalue;
否则,多维数组的成员都将是同一个数组。因此,当你的程序试图获得接下来的六个随机数时,不会发生任何事情,因为它们会使数组长度超过六个元素,这是程序阻止的。