如何從陣列中輸出唯一的隨機元素?

uj5u.com熱心網友回復:
你可以這樣做:
const getRand = function(arrayOfVals) {
const randIdx = Math.trunc(Math.random() * arrayOfVals.length);
return arrayOfVals[randIdx]
}
console.log(getRand([1, 2, 'a', 3, 'b', 'c']))
uj5u.com熱心網友回復:
我認為您希望在陣列中有一個隨機專案并預先洗掉所有重復項,這樣重復項就不會增加被輸出的機會。如果這是真的,這個函式應該可以幫助你:
const inputArray = [1, 2, 3, 3, 3, 3];
const getRandomArrayItem = (arr) => {
// Filter out all the duplicates
const uniqueArray = [...new Set(arr)];
// Get random array index
const randomIndex = Math.floor(Math.random() * uniqueArr.length);
return uniqueArray[randomIndex];
};
console.log(
getUniqueRandomArrayItem(inputArray)
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/526598.html
標籤:javascript数组
上一篇:3D三角形光柵化成體素網格
