gpt4 book ai didi

javascript - 如何在 JavaScript 中将数组中的随机值分配给另一个数组中的项目(将名称数组分配给工作日数组)?

转载 作者:行者123 更新时间:2023-12-03 02:21:29 24 4
gpt4 key购买 nike

我有以下工作日数组:

var weekDays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

还有另一组员工:

var empl = ["Bill Smith", "Bob Brown", "Megan Stallion", "Seth Evermann", "Kelly Swartz", "Mike Belltooth"]; 

第二个阵列的员工必须在第一个阵列的其中一天工作,例如周一:比尔·史密斯等。

到目前为止我所拥有的是:

var weekDays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; 

for (var i = 0; i < weekDays.length; i++){
var empl = ["Bill Smith", "Bob Brown", "Megan Taylor", "Seth Evermann",
"Kelly Swartz", "Mike Woods"];

console.log( "Day: " + i + ";" + " Shift: " +
empl[Math.floor(Math.random()*empl.length)] + ";" );
}

结果是这样的:

Day: 0; Shift: Megan Taylor;
Day: 1; Shift: Mike Woods;
Day: 2; Shift: Seth Evermann;
Day: 3; Shift: Bill Smith;
Day: 4; Shift: Bill Smith;
Day: 5; Shift: Bill Smith;

但我需要它是 Day: Mon、Day: Tue、Day: Wed 等,而不是 Day: 0、Day: 1 等。

此外,我希望每个名字只能使用一次,这样每个人只能在其中一天工作。

结果应该是这样的:

Day: Mon; Shift: Bob Brown; 
Day: Tue; Shift: Megan Taylor;
Day: Wed; Shift: Bill Smith;
...

我非常感谢对此的任何帮助,谢谢。

最佳答案

你就快到了。使用 for of 语法和 splice:

var weekDays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; 
var empl = ["Bill Smith", "Bob Brown", "Megan Taylor", "Seth Evermann", "Kelly Swartz", "Mike Woods"];

for (var i of weekDays){
console.log(
"Day: " + i + ";" + " Shift: " +
empl.splice(Math.random()*empl.length|0, 1) + ";"
);
}

关于javascript - 如何在 JavaScript 中将数组中的随机值分配给另一个数组中的项目(将名称数组分配给工作日数组)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49138423/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com