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

时间:2018-03-06 19:19:44

标签: javascript arrays loops for-loop random

我有一周的工作日:

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; Shift: Bob Brown; 
Day: Tue; Shift: Megan Taylor; 
Day: Wed; Shift: Bill Smith; 
...

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

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

结果应该是这样的:

var proxies = []; // This new variable ("proxies") contains a reference to an empty array.

proxyHelper.proxies = proxies; // You assign the same reference to a property 
                               // (named "proxies") of the "proxyHelper"
                               // object. The "proxies" property points
                               // to the same empty array as the variable above.

proxyHelper.tester = function(win) {

    electron.ipcMain.on('saveProxies', function(event, data) {

        proxies = []; // You assign a new reference to the global variable
                      // "proxies", which points to a new empty array.
                      // At this point the reference assigned to
                      // "proxyHelper.proxies" is still the original
                      // empty array from line 1
        // ...
    }

    // ...
}

我真的很感激任何帮助,谢谢。

2 个答案:

答案 0 :(得分:1)

你几乎就在那里。使用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) + ";" ); }

&#13;
&#13;
{{1}}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你只是缺少一段代码。

此致:

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

更新:

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