从JavaScript对象中随机选择值

时间:2017-05-04 03:05:05

标签: javascript html

如何从对象中选择随机值(属性及其键)并将每个值附加到特定div?

    <div id="propertydiv"></div>
    <div id="valuediv"></div>

var student = {
                    name : "John Doe",
                    age : "28",
                    gender : "Male"
                };

2 个答案:

答案 0 :(得分:3)

如果你将对象的键放在一个数组中,那么你可以随意选择一个,也许是这样的:

&#13;
&#13;
var student = { name : "John Doe", age : "28", gender : "Male" };

var keys = Object.keys(student);
var randomKey = keys[Math.floor(Math.random()*keys.length)];
var randomValue = student[randomKey];

document.getElementById("propertydiv").innerHTML = randomKey;
document.getElementById("valuediv").innerHTML = randomValue;
&#13;
<div id="propertydiv"></div>
<div id="valuediv"></div>
&#13;
&#13;
&#13;

(多次运行上面的代码段以查看随机行为。)

进一步阅读:

答案 1 :(得分:1)

您可以将它用于像...这样的对象数组。

<div id="propertydiv"></div>
<div id="valuediv"></div>

<script>
var student = [
                { name : "John Doe", age : "28", gender : "Male" },
                { name : "Nazmul", age : "22", gender : "Male"},
                { name : "Nadir", age : "6", gender : "Male"}
              ];

var randomObject = Math.floor(Math.random()*student.length);
var keys = Object.keys(student[randomObject]);
var randomKey = keys[Math.floor(Math.random()*keys.length)];
var randomValue = student[randomObject][randomKey];

document.getElementById("propertydiv").innerHTML = randomKey;
document.getElementById("valuediv").innerHTML = randomValue;

</script>