生成和排序Javascript随机数

时间:2014-11-16 20:32:19

标签: javascript html

我开始在1到100之间打印1000个随机数,然后对所有1000个数字进行排序。

这里发生了一些错误。

如何使用Math.random()?

        <script type="text/javascript" language="Javascript">
function pick(n, min, max) {
    var values = [],
        i = max;
    while (i >= min)
        values.push(i--);
    var results = [];
    var maxIndex = max;
    for (i = 1; i <= n; i++) {
        maxIndex--;
        var index = Math.floor(maxIndex * Math.random());
        results.push(values[index]);
        values[index] = values[maxIndex];
    }
    return results;
}

function go() {
    var running = true;
    do {
        if (!confirm(pick(1000, 1, 100).sort(function(a, b) {
                return a - b;
            }))) {
            running = false;
        }
    } while (running)
}
</script>
</head>

<body>
         <h1>100  random number between 1 and 100</h1>
         <p><button onclick="go()">Click me</button> to start generating numbers.</p>
          <p>When the numbers appear, click OK to generate another set, or Cancel to stop.</p>
    </body>

1 个答案:

答案 0 :(得分:1)

如果你真的只想生成1000个随机数,然后对它们进行排序,那么下面就足够了:

function pick(n, min, max) {
    var results = [];
    for (i = 1; i <= n; i++) {
        var value = Math.floor(Math.random() * max + min);
        results.push(value);
    }
    return results;
}

function go() {
    var running = true;
    do {
        if (!confirm(pick(1000, 1, 100).sort(function (a, b) {
            return a - b;
        }))) {
            running = false;
        }
    } while (running)
}