简体   繁体   English

从Javascript记录数组中选择随机项并将其转换为数组

[英]Select random item from Javascript record array and convert it to array

How would I randomly select an item from the following Javascript record array, and then take the result and convert it into an array and then select a random item from it? 我如何从以下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",
        }
    ]

For example, if the second item is selected, then from the area field, I want to select one of either "Brickfields, Central Bletchley, Fenny Stratford, Water Eaton" and assign it to a variable. 例如,如果选择了第二项,那么我要从“区域”字段中选择"Brickfields, Central Bletchley, Fenny Stratford, Water Eaton"并将其分配给变量。

Function to get random integers where min, max are inclusive 获取最小值,最大值(包括最小值)的随机整数的函数

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

Function to find Random Value from passed variable plot 从传递的变量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];
}

And use it like 并像这样使用

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM