The different options for accessing random elements in an array using JavaScript/P5.js

Viewed 151

I am new to using JavaScript and the P5.js library. However, I have many years of experience in Processing and some understanding of Java.

I have worked out 3 ways that I can randomly access an element in an array. All appear to work however I was wondering what would be best practice. `

var cars = ["Saab", "Volvo", "BMW"];

var rm = Math.floor(Math.random() * cars.length); 
var ri = int(random(cars.length));
var words = random(cars);

The first 2 methods are familiar however the 3rd is a new concept, is this somthing that is unique to javaSript.

Thanks in advance

1 Answers

The random() function you're using is part of P5.js, not plain JavaScript.

The documentation describes the ways it can be used:

If no argument is given, returns a random number from 0 up to (but not including) 1.

If one argument is given and it is a number, returns a random number from 0 up to (but not including) the number.

If one argument is given and it is an array, returns a random element from that array.

If two arguments are given, returns a random number from the first argument up to (but not including) the second argument.

The first method is the same as Math.random(). You're using the second method when you use random(cars.length). And you're using the third method when you use random(cars).

Related