简体   繁体   中英

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). I think that's happening here, too. This is 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. 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. The issue was fixed by removing the .slice() instances in the push() statements:

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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