在Javascript中随机选择对象的可枚举属性

tle*_*man 3 javascript

在Javascript中给出类似字典的对象,例如{a:1, b:-2, c:42},是否有一种随机选择属性的简单方法?

在上面的例子中,我想有,将返回的函数a,bc随机.

我提出的解决方案如下:

    var proplist = []
    forEach(property in foo) {
        if(propertyIsEnumerable(foo[property]) {
            proplist.push(property);
        }
    }
    var n = proplist.length;
    // randomly choose property (randInt(n) returns a random integer in [0,n))
    proplist[randInt(n)];
Run Code Online (Sandbox Code Playgroud)

有没有比较惯用的方法呢?

Rob*_*b W 7

使用Object.keys(或甚Object.getOwnPropertyNames至)获取所有属性的列表.然后,通过乘以Math.random()列表的长度,选择一个随机属性.

var propList = {}; //...
var tmpList = Object.keys(propList);
var randomPropertyName = tmpList[ Math.floor(Math.random()*tmpList.length) ];
var propertyValue = propList[randomPropertyName];
Run Code Online (Sandbox Code Playgroud)


geo*_*org 5

对于underscore.js,这可能是非常惯用的:

 randomProp = _.shuffle(_.keys(obj))[0]
Run Code Online (Sandbox Code Playgroud)

编辑:实际上,应该使用_.sample它.