在这个javascript中随机输出

时间:2009-11-12 02:50:55

标签: javascript

我想将此脚本末尾的数字输出随机化。 现在它创建了一个按数字排序的随机图像名称列表,我希望将图像名称改组。

有什么建议吗?

我是JS的新手,把头发拉过来。

谢谢!

function check(value)
{
if ( value != Math.round(value) || value <= 0 )
        alert("You must enter a positive integer in each input box.");
}

    function randint( l, u )
// Returns an integer uniformly distributed over l..u.
{
    return l + Math.floor( Math.random() * ( u + 1 - l ));
}


function generate( )
{
var select = parseInt(document.form.num.value);
if ( isNaN(select) || select != parseFloat(select) || select <= 0 )
    {
        alert("The number of random numbers desired must be a positive integer.");
        return;
}
var minval = parseInt(document.form.min.value);
if ( isNaN(minval) || minval != parseFloat(minval) || minval <= 0 )
    {
        alert("The minimum value of the range must be a positive integer.");
        return;
}
var maxval = parseInt(document.form.max.value);
if ( isNaN(maxval) || maxval != parseFloat(maxval) || maxval <= 0 )
    {
        alert("The maximum value of the range must be a positive integer.");
        return;
}


    var index = 0;
    var remaining = maxval - minval + 1;

if ( remaining <= select )
{
    alert("The number of values to select must be less than the size of the range from which to select them.");
    return;
}



function pad(number, length) {

var str = '' + number;
while (str.length < length) {
str = '0' + str;
}

 return str;

}

document.form.out.value = "";
    for ( var i = minval; i <= maxval; i++ )
{
        if (Math.random() < ( select / remaining))
    {
        document.form.out.value = document.form.out.value + '/Users/poe/images/physics304/Principle_' + pad(i, 5) + '.jpg' + '\n';

        index++;
        select--;  
        }
        remaining--;
}

}

2 个答案:

答案 0 :(得分:2)

要将列表排序为随机顺序,您可以执行以下操作:

someArray.sort( function() { return (Math.random() - 0.5); } );

答案 1 :(得分:1)

我已经包含了我修改过的代码区域或添加逻辑的区域。

function randomOrderArraySort(){
  return Math.round( Math.random() )-0.5;
}

var imageListArray = new Array();

for ( var i = minval; i <= maxval; i++ )
{
    if (Math.random() < ( select / remaining))
    {
        imageListArray.push('/Users/poe/images/physics304/Principle_' + pad(i, 5) + '.jpg');

        index++;
        select--;  
    }
    remaining--;
}

imageListArray.sort( randomOrderArraySort ); // Randomize Sorting.

document.form.out.value = "";
for (var i = 0; i < imageListArray.length; i++) {
    document.form.out.value = document.form.out.value +
        imageListArray[i] + '\n';
}