skip to Main Content

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


  1. You can use an IIFE like this:

    let r = (e=>e[Math.random()*e.length|0])(["GET", "POST", "PUT", "DELETE"])
    
    console.log(r)

    Note that |0 is equivalent to Math.floor() when the number is less than 2^31

    Login or Signup to reply.
  2. The length of the array can be accessed as a property of the array literal using dot notation:

    ["GET", "POST", "PUT", "DELETE"].length;
    

    Hence you could generate a random element value using the following:

    console.log(["GET", "POST", "PUT", "DELETE"][Math.floor(["GET", "POST", "PUT", "DELETE"].length * Math.random())]);
    Login or Signup to reply.
  3. 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

    ["GET", "POST", "PUT", "DELETE"].sort(() => Math.random() - 0.5)[0]
    

    as .sort() sorts depending on if result is positive or negative, and Math.random() - 0.5 is equally randomly positive or negative


    Ways with variable

    function rndItem(HERE) { return HERE[Math.floor(Math.random() * HERE.length)] }
    rndItem(["GET", "POST", "PUT", "DELETE"])
    /* --- --- --- */
    [["GET", "POST", "PUT", "DELETE"]].map(HERE => HERE[Math.floor(Math.random() * HERE.length)])
    /* --- --- --- */
    Array.prototype.rand = function(){return this[Math.floor(Math.random() * this.length)]}
    ["GET", "POST", "PUT", "DELETE"].rand()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search