gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:34:01 24 4
gpt4 key购买 nike

如何从以下 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”之一并将其分配给变量。

最佳答案

获取随机整数的函数,其中 min、max 包含在内

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))

关于javascript - 从Javascript记录数组中选择随机项并将其转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28671893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com