I’d like to do something like this to generate some text blocks with a little variety:
["GET", "POST", "PUT", "DELETE"][Math.floor(Math.random() * this.length)]
Is it possible to reference the length
property without first saving the array as a var? I’d like to do this in a one line so it’s simpler to put this into string literals with minimal extra steps.
3
Answers
You can use an IIFE like this:
Note that
|0
is equivalent to Math.floor() when the number is less than 2^31The length of the array can be accessed as a property of the array literal using dot notation:
Hence you could generate a random element value using the following:
There is no way to reference an array in two places without literally assigning it to a variable in at least some way.
There is an easy way to get a random item without any variables tho
as
.sort()
sorts depending on if result is positive or negative, andMath.random() - 0.5
is equally randomly positive or negativeWays with variable