[英]Select random item from Javascript record array and convert it to array
我如何從以下Javascript記錄數組中隨機選擇一個項目,然后將結果轉換為數組,然后從中選擇一個隨機項目?
plot = [
{
postcode: "MK1",
area: "Denbigh, Mount Farm",
},
{
postcode: "MK2",
area: "Brickfields, Central Bletchley, Fenny Stratford, Water Eaton"
},
{
postcode: "MK3",
area: "Church Green, Far Bletchley, Old Bletchley, West Bletchley",
},
{
postcode: "MK4",
area: "Emerson Valley, Furzton, Kingsmead, Shenley Brook End, Snelshall West, Tattenhoe, Tattenhoe Park, Westcroft, Whaddon, Woodhill",
},
{
postcode: "MK5",
area: "Crownhill, Elfield Park, Grange Farm, Oakhill, Knowlhill, Loughton, Medbourne, Shenley Brook End, Shenley Church End, Shenley Lodge, Shenley Wood",
}
]
例如,如果選擇了第二項,那么我要從“區域”字段中選擇"Brickfields, Central Bletchley, Fenny Stratford, Water Eaton"
並將其分配給變量。
獲取最小值,最大值(包括最小值)的隨機整數的函數
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
從傳遞的變量plot
查找隨機值的函數
function getRandomValue(plot)
{
var rN1 = getRandomInt(0,plot.length-1);
var areaArray= plot[rN1].area.split(",");
var rN2 = getRandomInt(0,areaArray.length-1);
return areaArray[rN2];
}
並像這樣使用
plot = [
{
postcode: "MK1",
area: "Denbigh, Mount Farm",
},
{
postcode: "MK2",
area: "Brickfields, Central Bletchley, Fenny Stratford, Water Eaton"
},
{
postcode: "MK3",
area: "Church Green, Far Bletchley, Old Bletchley, West Bletchley",
},
{
postcode: "MK4",
area: "Emerson Valley, Furzton, Kingsmead, Shenley Brook End, Snelshall West, Tattenhoe, Tattenhoe Park, Westcroft, Whaddon, Woodhill",
},
{
postcode: "MK5",
area: "Crownhill, Elfield Park, Grange Farm, Oakhill, Knowlhill, Loughton, Medbourne, Shenley Brook End, Shenley Church End, Shenley Lodge, Shenley Wood",
}
]
console.log(getRandomValue(plot))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.