简体   繁体   English

使用相同的参数JavaScript多次调用一个函数

[英]Invoke a function multiple times with the same argument JavaScript

I'm writing a "Secret Santa" function that takes an array of names and matches them randomly with other names in the same array (and they can't match with themselves). 我正在编写“ Secret Santa”函数,该函数需要一个名称数组,并将它们与同一数组中的其他名称随机匹配(它们本身不能匹配)。

I've got the initial portion working, but now I need to make it so it runs the function twice, and then make sure no one gets the same person two years in a row. 我已经开始工作了,但是现在我需要使它运行两次,以便确保该函数运行两次,然后确保连续两年没有人遇到同一个人。 For the life of me, I cannot get the function to run twice and create two separate outputs (except with console.log, but since I need to compare the outputs that won't help me). 为了我自己的一生,我无法让函数运行两次并创建两个单独的输出(console.log除外,但由于我需要比较对我无济于事的输出)。

Code: 码:

var family = ['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff', 'ggg', 'hhh', 'iii']

function secretSanta() {
var yourPick = [];
var receivers = family.slice();
var length = family.length;
for (var i = 0; i < length; i++) {
  var giver = family[i];
  var receiverIndex = Math.floor(Math.random() * receivers.length);
     while (receivers[receiverIndex] === giver) {

       receiverIndex = Math.floor(Math.random() * receivers.length);
     }
     var receiver = receivers.splice(receiverIndex, 1)[0];
    yourPick.push({
      Giver: giver,
      Receiver: receiver
    });
}
return yourPick;
}
secretSanta()

I've tried iteration 我尝试过迭代

for (var i = 1; i < 3; i++) secretSanta(i)

Recursion 递归

(function repeat(number) {
    secretSanta(number);
    if (number < 3) repeat(number + 1);
})(1);

and functor application 和函子应用

[1, 2, 3].forEach(secretSanta);

But I either get undefined, an infinite loop, or "maximum stack size exceeded" 但是我要么无法定义,无限循环,要么“超出最大堆栈大小”

Thanks for everyone's help! 感谢大家的帮助!

All possible different pairs in random order. 所有可能的不同对都以随机顺序排列。

 var family = ['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff', 'ggg', 'hhh', 'iii'] var pairs = []; for(let i = 0; i<family.length; i++){ for(let j = i+1; j<family.length; j++){ pairs.push([family[i], family[j]]) } } while(pairs.length){ let pair = Math.floor(Math.random() * pairs.length) let temp = pairs.splice(pair,1); if(Math.floor(Math.random()*2)) temp[0].reverse()//<-- pair order console.log(temp[0].join(" - ")) } 

The while is just to pick the pairs randomly. 而一会儿只是随机挑选一对。

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

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