如何创建一个随机的JS对象?

时间:2014-08-18 14:33:37

标签: javascript object random

我想知道是否有一种方法可以创建随机化的JavaScript对象。理解随机化:生成的对象具有一组随机属性,每个属性都有一个随机名称。问题归结为两个:

1)是否可以在运行时创建对象,而无需事先指定属性数量?

2)是否可以随机化对象属性的名称?

我正在寻找解释/解决方案,而不仅仅是答案。

2 个答案:

答案 0 :(得分:0)

一种非常粗暴的方式,无法想到它的任何用例:

function randomObject(){
    var ret = {};
    var propertyCount= Math.random() * 10;
    for (var x = 0; x < propertyCount; x++ ){
        ret[Math.random()] = Math.random(); 
    }
    return ret;
}

答案 1 :(得分:0)

我不知道它是如何有用的,但是,是的,这是可能的。

var MAX_PROPERTIES = 50;
var ALLOWED_CHARACTERS_IN_KEY = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
var MAX_KEY_LENGTH = 30;

var object = {};
var propertiesCount = Math.round(Math.random() * MAX_PROPERTIES);
for(var i = 0 ; i < propertiesCount ; i++) {
    var keyLength = Math.round(Math.random() * MAX_KEY_LENGTH);
    var randKey = "";
    for(var j = 0 ; j < keyLength ; j++) {
        randKey += ALLOWED_CHARACTERS_IN_KEY[Math.floor(Math.random() * ALLOWED_CHARACTERS_IN_KEY.length)];
    }

    var randValue = Math.random();
    object[randKey] = randValue;
}

请注意,某些键可以以数字开头,但不能用点表示法调用。

示例:

{
    "NmkQZWeW9_ojadERwK74HXYj43Lw":0.3039316821878978,
    "PZiFauEC6H":0.04273172815465165,
    "2m7cMrwRPoxpa8LvmpAaJ":0.7010494474513925,
    "D":0.4552683870622114,
    "HQhIxPxO8tsdocRuGJpnhB7k2PjD":0.18360190519964337,
    "rVwM8":0.8681098855694265,
    "3Vf5HGYDOmUli3":0.527829742115212,
    "fQ4ryGL2cxhJeRd":0.10353706566292953,
    "D_DQqODu_":0.1272988336424956,
    "8UY0a7":0.17057184875868092,
    "8i1uVtPwzl0KRA8iYZ4uKcPKF":0.9554370948377217,
    "TTi":0.038665872114993616,
    "YofUj9RrK7foQrl":0.5835241172217945,
    "sb3SzEB_":0.17136910050721899,
    "801FopHCCML4ozrfmjak":0.10999126507324442,
    "D8":0.05981337403919851,
    "oL8ZZvrAG":0.36816486041399255,
    "hfXxJ0sNp42y2HYEDXLBYgZ6mV":0.13977757384990708,
    "2xx4AJrQswA5TIcXr":0.8610074761855161,
    "68RNcKQmgnh_qTG":0.5234909406332302,
    "wJsV8BRo1cT2MtXDuh":0.4497261910215308,
    "6yFr4E81bvXK":0.5996413679577888,
    "Px2bjBvFSBu":0.017922504534248707,
    "yazK1KQbmUhE4Ul1rZX5hf0yulX_JK":0.7105144243046027,
    "cXmdnvmP":0.028121925940253756,
    "R_fDjw9yBejk3":0.699514797889162,
    "z":0.34347612922580006,
    "2kTX6Q2tzbCo3":0.678962211994213
}