Generate random numbers from string in JavaScript

╄→尐↘猪︶ㄣ 提交于 2019-12-04 19:22:38

My current solution uses the CryptoJS library's MD5 hashing function to generate a random number:

// seed is the user's random number

choose_option = function(seed, test_name, options) {
  word = CryptoJS.MD5("" + seed + test_name).words[0]; // take first 32-bit word
  i = Math.abs(word % options.length);
  return options[i];
}

Maybe a bit later and a bit exagerate as the lib in question has many feature you may not use, but I always have this included in my projects so let me expose my solution to the very same problem you had. This lib can be initalized with a seed (chancejs#seed), very useful for creating repeatable results:

const Chance = require('chance');
c1 = Chance('email@gmail.com', 'maybe a uuid here');
c1.integer();
c1.natural({min:1000,max:9999});

c2 = Chance('foo-baz-bar');
c2.string();
c2.word();
...

hope this helps.

var availNum= [1, 4, 5, 6, 7, 8, 12];
//@var count number of random num you want 
function createRandomData(count) {
    var data = [],
    for (var i = 0; i < count; i++) {
        var random = availNum[Math.floor(Math.random() * availNum.length)],

        data.push({
          random:random 
        });
    }
    return data;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!