2017-05-04 167 views
0

如何從對象中選擇隨機值(屬性及其鍵)並將每個值附加到特定的div?從JavaScript對象中隨機選擇值

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

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

回答

2

如果你把對象的關鍵在一個數組,那麼你可以很容易地選擇一個隨機的,也許有點像這樣:

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;
<div id="propertydiv"></div> 
 
<div id="valuediv"></div>

(運行上面的代碼段幾次看到隨機行爲)

更多閱讀:

+0

謝謝:)它的工作原理。 –

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>