English 中文(简体)
带有 Javascripter 或 jquery 的随机数
原标题:Random Number with javascript or jquery

我试图在两个数字之间选择随机数字的脚本。 但是它有时会选择相同的数字。 我不想重复相同的数字, 直到数组完成 。

这是我的代码

$(document).ready(function () {
    abc();
    test = array();

    function abc() {
        res = randomXToY(1, 10, 0);

        $( #img  + res).fadeTo(1200, 1);
        //$(this).addClass( activeImg );
        //});
        setTimeout(function () {
            removeClassImg(res)
        }, 3000);
    }

    function removeClassImg(res) {
        $( #img  + res).fadeTo(1200, 0.1);
        //$( #img  + res).removeClass( activeImg );
        abc();
    }

    function randomXToY(minVal, maxVal, floatVal) {
        var randVal = minVal + (Math.random() * (maxVal - minVal));

        return typeof floatVal ==  undefined  ? Math.round(randVal) : randVal.toFixed(floatVal);

    }
});

有没有人知道这件事...

最佳回答

您需要保留一个已经生成的数字列表, 并对照此列表检查 。 如果您发现一个假名, 将重新生成一个新的数字 。

问题回答

如果您不希望随机数字重复重复自己的话, 您必须跟踪某条路的路径 。

如果您所处理的范围相对小,您可以创建一个包含所有可能结果的阵列,并随机选择。

function Randomizer(minVal, maxVal, floatVal){
    var possible_results = []; // for larger arrays you can build this using a loop of course
    var randomization_array = [];
    var count = minVal;
    var incrementor = floatVal || 1; // set the distance between possible values (if floatVal equals 0 we round to 1)
    while (count <= maxVal) {
        possible_results.push(count);
        count += incrementor;
    }

    this.run = function(){
        // if randomization_array is empty set posssible results into it
        randomization_array = randomization_array.length ? randomization_array : $.merge(randomization_array, possible_results);
        // pick a random element within the array
        var rand = Math.floor(Math.random()*randomization_array.length);
        // return the relevant element
        return randomization_array.splice(rand,1)[0];   
    }
}

并且为了使用它(为每一可能的射程设计一个专用物体):

rand = new Randomizer(1,10,0);
rand.run();

指出这一方法在非常大的范围内效果不佳。





相关问题
CSS working only in Firefox

I am trying to create a search text-field like on the Apple website. The HTML looks like this: <div class="frm-search"> <div> <input class="btn" type="image" src="http://www....

image changed but appears the same in browser

I m writing a php script to crop an image. The script overwrites the old image with the new one, but when I reload the page (which is supposed to pickup the new image) I still see the old one. ...

Firefox background image horizontal centering oddity

I am building some basic HTML code for a CMS. One of the page-related options in the CMS is "background image" and "stretch page width / height to background image width / height." so that with large ...

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签