如果我有一个二维数组,并且每行中的元素数量不同。如何从该数组中获取随机元素?有没有人有最好的解决方案?
arr = [
[2,3,4],
[3,4]
[1,22,3,45]
]
发布于 2021-02-25 02:50:40
使用Array.flat()展平输入数组并获得随机元素。
const arr = [
[2,3,4],
[3,4],
[1,22,3,45]
];
const flattenArr = arr.flat();
const randomIndex = Math.floor(Math.random()*flattenArr.length);
console.log(flattenArr[randomIndex]);
发布于 2021-02-25 02:55:18
const arr = [
[2, 3, 4],
[3, 4],
[1, 22, 3, 45],
];
const flatArray = arr.reduce((acc, curr) => {
return [...acc, ...curr];
}, []);
function getRandomNumber(len) {
return Math.floor(Math.random() * len);
}
const randomNumber = getRandomNumber(flatArray.length);
console.log(flatArray[randomNumber]);
发布于 2021-02-25 02:56:58
你可以得到一个介于0和嵌套数组长度之间的随机索引,试试这个:
let arr = [
[2,3,4],
[3,4],
[1,22,3,45]
]
let result = [];
for(let i = 0; i < arr.length; i++){
result.push(arr[i][Math.floor(Math.random() * arr[i].length + 0)]);
}
console.log(result);
https://stackoverflow.com/questions/66361640
复制相似问题