从JavaScript对象中随机选择值 [英] randomly select value from a JavaScript object

查看:118
本文介绍了从JavaScript对象中随机选择值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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


推荐答案

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

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;

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

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

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

Furthe阅读:

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

这篇关于从JavaScript对象中随机选择值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆