我正在尝试制作一个从数组中选择随机字符串的javascript,并且这样做,但是在输出后它始终显示“unidentified”。除了我要尝试执行10-20次这样的事实外,这不会是一个大问题,这会使10-20个“unidentifieds”在尝试读取字符串时遇到麻烦。

//Draw random contestants for a game show!

var contestants = ["Alejandro", "Amy", "AnnMaria", "B", "Beardo", "Beth", "Blainley", "Brick", "Bridgette", "Cameron", "Cody", "Courtney", "Dakota", "Dave", "Dawn", "DJ", "Duncan", "Ella", "Eva", "Ezekiel", "Geoff", "Gwen", "Harold", "Heather", "Izzy", "Jasmine", "Jo", "Justin", "Katie", "Leonard", "Leshawna", "Lightning", "Lindsey", "Max", "Mike", "Noah", "Owen", "Rodney", "Sadie", "Sam", "Samey", "Scarlett", "Scott", "Shawn", "Sierra", "Sky", "Staci", "Sugar", "Tofur", "Trent", "Tyler", "Zoey"];

var randomContestant = function () {
  console.log(contestants[Math.floor(Math.random() * 52)]);
};

//randomContestant(); to pick a random contestant.

var drawContestants = function (howMany) {
  for (var i = 0 ; i < howMany; i++) {
    console.log (randomContestant(i + howMany));
  }
};

//drawContestants(numberOfContestantsYouWantDrawn); to draw a number of random contestants.


从我看过的其他问题来看,这与该函数的参数为​​空的事实有关吗?如果那是问题,我应该放在那儿,以便在输出后停止提供“Unidentified”?

(我现在才使用javascript几天,因此,如果这个问题已得到回答,我可能会错过那个问题,或者因为它更高级而无法理解他们对此的回答。)

最佳答案

您正在将参数传递给randomContestant,但未在其中的函数中使用它。您也不会删除已选择的参赛者。尝试这样的事情:

const contestants = ["Alejandro", "Amy", "AnnMaria", "B", "Beardo", "Beth", "Blainley", "Brick", "Bridgette", "Cameron", "Cody", "Courtney", "Dakota", "Dave", "Dawn", "DJ", "Duncan", "Ella", "Eva", "Ezekiel", "Geoff", "Gwen", "Harold", "Heather", "Izzy", "Jasmine", "Jo", "Justin", "Katie", "Leonard", "Leshawna", "Lightning", "Lindsey", "Max", "Mike", "Noah", "Owen", "Rodney", "Sadie", "Sam", "Samey", "Scarlett", "Scott", "Shawn", "Sierra", "Sky", "Staci", "Sugar", "Tofur", "Trent", "Tyler", "Zoey"];

const randomContestant = function (pool) {
  return pool[Math.floor(Math.random() * pool.length)];
};

const drawContestants = function (howMany) {
  // make a copy so as not to mutate the original array
  let contestantPool = contestants.slice();
  for (let i = 0 ; i < howMany; i++) {
    const pick = randomContestant(contestantPool);
    console.log(pick);
    const index = contestantPool.indexOf(pick);
    contestantPool =
    [...contestantPool.slice(0, index),
     ...contestantPool.slice(index + 1),
    ];
  }
};

drawContestants(10);

关于javascript - 无参数的函数输出后不明,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49765253/

10-09 22:40