繁体   English   中英

从数组中获取 2 个唯一值

[英]Getting 2 unique values from array

我有以下任务 - 我需要选择 2 个不相等的值形成值数组。 我想用 if / loop 逻辑来理解基础。 我已经成功完成了我的任务,但在我看来,我的循环并没有结束,并且几次刷新后的页面崩溃了。

我们将非常感谢您对我的代码的帮助。

 var arrP = []; var randomPersons = 2; var nsm = ["Value 1", "Value 2", "Value 3", "Value 4", "Value 5"]; function randomGen() { for (i=0; i<randomPersons; i++) { var rnd = Math.floor(Math.random() * (nsm.length)); arrP.push(rnd); } } do { randomGen(); } while (arrP[0] === arrP[1]); document.write(nsm[arrP[0]] + "<br>" + nsm[arrP[1]]);
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title></title> </head> <body> </body> </html>

一个相当幼稚的实现可能是这样的。 (例如,更优化的东西不需要修改输入数组。)

它假设arr是选择的“袋子”,根本不考虑平等。 换句话说,如果你的“包”是["John", "John", "Peasoup", "Booze", "Scaffold"] ,那么输出中可能会出现两个 John。

 function pickRandom(arr, num) { const output = []; const input = [...arr]; // shallow-copy so we can modify it // work to do and choices to pick? while(input.length > 0 && output.length < num) { // Pick random remaining index... const index = Math.floor(Math.random() * input.length); const [pick] = input.splice(index, 1); // Remove from input output.push(pick); // ... put into output } return output; } var picks = pickRandom(["Value 1", "Value 2", "Value 3", "Value 4", "Value 5"], 2); document.getElementById("x").value = JSON.stringify(picks, null, 2);
 <textarea id="x" rows="10" cols="30"></textarea>

暂无
暂无

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

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