简体   繁体   English

从 HTML 输入字段创建随机 javascript 数组

[英]Creating a Random javascript array from an HTML input field

I have basic HTML form that asks for a number between 1 and 10. Based on that number I want to create a new array.我有一个基本的 HTML 表单,要求输入 1 到 10 之间的数字。基于该数字,我想创建一个新数组。 For now the code shows an alert box of the new created array, but eventually it will be a table that displays the results.现在,代码显示了新创建数组的警告框,但最终它将是一个显示结果的表格。 The current array has 10 values and I want it generate a new array randomly.当前数组有 10 个值,我希望它随机生成一个新数组。 I think I have it and just missing one thing or maybe a few.我想我拥有它,只是缺少一件事或几件事。

function createRandomArray () {

var numOfGamesElement = document.getElementById("numOfGames");
var numOfGames = numOfGamesElement.value;

var gamesPicked [];

  const boardGames = ["UNO", "Monopoly", "Clue", "Pandemic", "Catan", "Articulate!", "Codenames", "Fallout", "Candy Land", "Scrabble"];


let gamesPicked = boardGames[Math.floor(Math.random() * boardGames.length)];

for(let i = 0; i < numOfGames; i++){
  gamesPicked.push(i);
}
  alert(gamesPicked.join("\n"));
//createTable(gamesPicked)
}

One issue is you might get duplicates in your randomized gamespicked array.一个问题是您的随机游戏选择数组中可能会出现重复项。 It might be better to shuffle the array (randomize it) and then just get the slice of X items, like this.打乱数组(随机化)然后只获取 X 项的slice可能会更好,就像这样。 Notice that I change the numOfGames value from a string to a number by prepending it with +请注意,我通过在前面加上+numOfGames值从字符串更改为数字

/* Randomize array in-place using Durstenfeld shuffle algorithm */
function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}    
const boardGames = ["UNO", "Monopoly", "Clue", "Pandemic", "Catan", "Articulate!", "Codenames", "Fallout", "Candy Land", "Scrabble"];    
function createRandomArray () {
   let numOfGames = +document.getElementById("numOfGames").value || 0;
   let gamesPicked = shuffleArray(boardGames).slice(0, numOfGames)
   alert(gamesPicked.join("\n"));
}

You can do it using vanilla JS like this你可以像这样使用vanilla JS来做到这一点

function samples(array, length) {
    var samplesSet = new Set();
    if (array.length < length) {
        throw Error("requested length is greater than given array");    
    }
    while(samplesSet.size < length) {
        samplesSet.add(array[Math.floor(Math.random() * array.length)]);
    }
    return [...samplesSet];
}
function createRandomArray () {

var numOfGamesElement = document.getElementById("numOfGames");
var numOfGames = numOfGamesElement.value;

  const boardGames = ["UNO", "Monopoly", "Clue", "Pandemic", "Catan", "Articulate!", "Codenames", "Fallout", "Candy Land", "Scrabble"];


let gamesPicked = samples(boardGames, numOfGames);
  alert(gamesPicked.join("\n"));
//createTable(gamesPicked)
}

Or using lodash sampleSize like this或者像这样使用lodash sampleSize

let _ = require('lodash');

function createRandomArray () {

var numOfGamesElement = document.getElementById("numOfGames");
var numOfGames = numOfGamesElement.value;

  const boardGames = ["UNO", "Monopoly", "Clue", "Pandemic", "Catan", "Articulate!", "Codenames", "Fallout", "Candy Land", "Scrabble"];


let gamesPicked = _.sampleSize(boardGames, numOfGames);
  alert(gamesPicked.join("\n"));
//createTable(gamesPicked)
}

This works but does not address that the random function can pick duplicates.这有效,但没有解决随机函数可以选择重复项的问题。

<!DOCTYPE html>
<head>
<script>
function createRandomArray () {
    var numOfGamesElement = document.getElementById("numOfGames");
    var numOfGames = numOfGamesElement.value;

    const boardGames = ["UNO", "Monopoly", "Clue", "Pandemic", "Catan", "Articulate!", "Codenames", "Fallout", "Candy Land", "Scrabble"];

    var gamePicked;
    var gamesPicked = {};
    for(let i = 0; i < numOfGames; i++){
      gamePicked = boardGames[Math.floor(Math.random() * boardGames.length)];
      gamesPicked[i] = gamePicked;
      alert(gamesPicked[i]);
    }
    // could build table here
}
</script>
</head>

<body>
<label>Number of games (1 to 10):
<input id="numOfGames">
</label>
<button onclick="createRandomArray()">Click Me</button>
</body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM