简体   繁体   English

JS中数组元素的随机子集

[英]Random subset of array elements in JS

I'm trying to select a random set of three unique elements from an array. 我正在尝试从数组中选择三个唯一元素的随机集合。 I'm newish to JS, and I'm constantly tripping over reference behavior that is unexpected (Python is my best language). 我是JS的新手,而且我经常遇到意外的参考行为(Python是我最好的语言)。 I think that's happening here, too. 我认为这也在发生。 This is P5.JS. 这是P5.JS。

Here's my attempt: 这是我的尝试:

var points = [[0,0],[.5*w,0],[w,0],
[0,.5*h],[.5*w,.5*h],[w,.5*h],
[0,h],[.5*w,h],[w,h]];

var vert = [];
var start = int(random(0,8));
vert.push(points[start].slice());
points.splice(start,1);

var middle = int(random(0,7));
vert.push(points[middle].slice());
points.splice(middle,1);

var end = int(random(0,6));
vert.push(points[end].slice());

When I look at the contents of vert , it's clear that I'm not getting the elements that I expected. 当我查看vert的内容时,很明显我没有得到我期望的元素。 In particular, I'm never getting any of the last three elements in the original array. 特别是,我永远不会获得原始数组中的最后三个元素。

As noted above, the int() and random() are p5.js functions, and fine. 如上所述, int()random()是p5.js函数,很好。 The issue was fixed by removing the .slice() instances in the push() statements: 通过删除push()语句中的.slice()实例来解决此问题:

var vert = [];

var start = int(random(0,8));
vert.push(points[start]);
points.splice(start,1);

var middle = int(random(0,7));
vert.push(points[middle]);
points.splice(middle,1);

var end = int(random(0,6));
vert.push(points[end]);

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

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