使用JavaScript在数组中计算数字到数字

时间:2015-10-16 01:59:18

标签: javascript jquery arrays random difference

我正在制作一个随机数生成器来分配任务。我想给每个人一个随机数,然后生成随机数。然后我想按照它们的接近程度列出人员。

我想可能会迭代数组并找到winningNumber和数字之间的绝对差异。但是,我不确定如何将数字链接回列表中的名称。

我如何评估这些数字?

Fiddle here.

HTML:     

随机数分配器

<p>Have tasks to assign but no volunteers? Sign them up here</p>
<div id="input-area">
<input type="text" placeholder="Lucky person here" id="input">
<button id="button">Add Them!</button>
<br>
<br>
<button id="random">Generate Random Number</button>
</div>
<hr>
<div id="list-area">
<ul id="list"></ul>
</div>

CSS:

#input-area {
width: 100%;
border: 1px solid black;
}

JavaScript的:

function randomNumber() {
return Math.round((Math.random()) * 100);
};
var randomNumberValue;
var winningNumber;
var myArray = [];
$(document).ready(function () {
console.log("The JavaScript has loaded");
$('#button').on('click', function () {
    randomNumberValue = randomNumber();
    var inputValue = $('#input').val();
    if (inputValue === "") {
        return;
    };
    $('#list').append("<ul>" + inputValue + ": " + randomNumberValue + "             </ul>");
    myArray.push(randomNumberValue);
    $('#input').val("");
});
$('#random').on('click', function () {
    myArray.sort();
    winningNumber = randomNumber();
    if (winningNumber === 0) {
        winningNumber++;
    };
    console.log(myArray);
    console.log("The winning number is: " + winningNumber);
    for (var i = 0; i < myArray.length; i++) {
        i - winningNumber;
    };
    console.log(myArray);
});
});

1 个答案:

答案 0 :(得分:1)

有一些小的改编:

function randomNumber() {
  return Math.round((Math.random()) * 100);
};
var randomNumberValue;
var winningNumber;
var myArray = [];
$(document).ready(function () {
    console.log("The JavaScript has loaded");
    $('#button').on('click', function () {
        var randomNumberValue = randomNumber();
        var inputValue = $('#input').val();
        if (inputValue === "") {
            return;
        };
        // an item in a list is the <li> element
        $('#list').append("<li>" + inputValue + ": " + randomNumberValue     + " </li>");
        // to simplify things I've used normal arrays for storage
        // instead of a list of {key:value} pairs
        // Advantage of {key:value} pairs here would be an easier check for multiple name entries
        myArray.push([randomNumberValue,inputValue]);
        $('#input').val("");
    });
    $('#random').on('click', function () {
        // not needed in this simple algorithm
        // You can use a binary search if the array is sorted which would make it faster
        // but also much more complicated and isn't worth the hassle for small lists
        //myArray.sort();
        var winningNumber = randomNumber();
        // get the first number for a start (numbering starts at zero)
        var current = myArray[0][0];
        // we need something to keep the position of the entry
        var pos = 0;
        console.log("The winning number is: " + winningNumber);
        for (var i = 0; i < myArray.length; i++) {
            // the actual number at position i in the array
            var value = myArray[i][0];
            /*
                  Compute two differences
                  a) between the drawn number and the actual number
                  b) between the drawn number and the last number that was
                     nearest to the last actual number

                  If the actual difference a is smaller than the last difference
                  it is better, hence we keep it. We have to know where it was to
                  be able to name the winner and keep the position to do so.
             */ 
            if(Math.abs(winningNumber - value) < Math.abs(winningNumber - current)){
                current = value;
                pos = i;
            }
            // No "else" here because, well, we don't need to do anything, just go on
            // until something is found.
        };
        console.log("The winner is: " + myArray[pos][1]);
        console.log(myArray.join(" | "));
    });
});

有一点需要注意:您不会检查双重条目。名称和随机数都可以重复,需要检查,否则可能会以奇怪的方式失败。