randomly select value from a JavaScript object

前端 未结 2 1367
感情败类
感情败类 2021-01-25 20:55

How do I select random value (property and its key) from the object and append each one to specific div?

    
<
2条回答
  •  不知归路
    2021-01-25 21:19

    If you put the object's keys in an array then you can easily select one at random, maybe a little something like this:

    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;

    (Run the snippet above several times to see the random behaviour.)

    Further reading:

    • Object.keys()
    • Math.random()
    • Math.floor()

提交回复
热议问题