在Javascript中随机化值 [英] Randomize value in Javascript

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

问题描述

我需要在JS中随机化一组值,然后我将函数随机调用三次。我怎么能记住并阻止随机发生器给我以前给我的结果?我只能给一个值一次。

I need to randomize set of values in JS, and I call function randomize for example three times. How can I remember and block random generator from giving me results that it gave me previous times? I can only give one value once.

var value = Math.floor(Math.random() * 11);


推荐答案

使用记忆模式。

var randomize = (function () {
    var memo = [],
        maxlen = 10;
    return function() {
        if (memo.length === maxlen) {
            throw new Error('Out of values');
        }
        var value = Math.floor(Math.random() * (maxlen + 1));
        if (memo.indexOf(value) !== -1) {
            return randomize();
        }
       memo.push(value);
       return value;
    };
}());

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

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