[英]How to implement random items to display for a mapping function?
我有一個映射 function 迭代一個項目數組。 我已經將數據切片到 select 只顯示一小部分數據。 但是現在我還希望映射到數組中的 select 隨機項。
const randomStocks = Math.floor(Math.random() * buckets.stock_count);
這是我的映射 function:
{bucket.stock_list.slice(0, 4).map((stock, index) =>
{return(
<Chip key={index} label={stock} />
)}
)}
在尊重數據切片的同時,我可以在哪里以及如何在映射 function 中添加我的randomStocks
?
如果你的數組不是很大,那么一個實用的解決方案是首先隨機打亂你的數組,然后像你已經做的那樣slice
。
對於改組,您可以使用我如何改組數組中提供的答案之一:
function shuffle(a) { var j, x, i; for (i = a.length - 1; i > 0; i--) { j = Math.floor(Math.random() * (i + 1)); x = a[i]; a[i] = a[j]; a[j] = x; } return a; }
那么你的代碼可以是:
{
shuffle(Array.from(bucket.stock_list)).slice(0, 4).map((stock, index) => {
return(
<Chip key={index} label={stock} />
)
})
}
僅當您不想改變股票列表本身並保持其原始順序不變時,才需要調用Array.from
。
您可以使用來自Math.Random()
的以下隨機 integer 生成器:
const ITEMS_LIMIT = 4;
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}
const randomStocks = getRandomInt(0, buckets.stock_count - ITEMS_LIMIT);
然后你可以做
{
bucket.stock_list.slice(randomStocks, randomStocks+ ITEMS_LIMIT).map((stock, index) => {
return <Chip key={index} label={stock} />
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.