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

时间:2015-02-23 10:43:53

标签: javascript arrays

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

1 个答案:

答案 0 :(得分:1)

获取随机整数的函数,其中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))