How to employ Math.random with multiple variables in JavaScript

Within a function, I have the following statement:

 Math.random() > 0.5 ? 'spikes' : 'slime' 

I am interested in adding one more variable, let's call it 'stone', and having the program randomly choose between those three options. How can I modify the statement to achieve this without utilizing arrays? Any guidance on this matter would be greatly appreciated as I am a novice and finding difficulty comprehending this open source code.

Answer №1

Using an array is definitely the optimal choice:

var result = ['spikes', 'slime', 'stone'][Math.floor(Math.random() * 3)];

console.log(result);

While switch/case can work, it requires more code compared to using an array:

function getRandom() {
  var num = Math.floor(Math.random() * 3);

  switch (num) {
    case 0:
      return 'spikes';

    case 1:
      return 'slime';

    default:
      return 'stone';
  }

}

console.log(getRandom());

Answer №2

Using arrays is an efficient method. All you need to do is create an array with the options you want and then randomly select one.

Array.prototype.selectRandom = function() {
  return this[Math.floor(Math.random() * this.length)];
}

// example without modifying Array.prototype
function chooseRandom(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}

var items = ['apple', 'banana', 'cherry', 'date', 'orange', 'pear', 'strawberry'];

document.write([items.selectRandom(), chooseRandom(items)].join('<br />'));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What makes 'Parsing JSON with jQuery' unnecessary?

Just performed an ajax request with a query and noticed that my response is already in the form of a JavaScript object. When I try to parse the JSON using: var obj = jQuery.parseJSON(response); 'obj' turns out to be null, yet I can directly ac ...

Looking to introduce Vue.js into an established SSR website?

Can Vue be used to create components that can be instantiated onto custom tags rendered by a PHP application, similar to "custom elements light"? While mounting the Vue instance onto the page root element seems to work, it appears that Vue uses the entire ...

Promise and Determination failing to produce results

const { GraphQLServer } = require('graphql-yoga'); const mongoose = require('mongoose'); mongoose.connect("mongodb://localhost/test1"); const Todo = mongoose.model('Todo',{ text: String, complete: Boolean }); const ...

Looking to Move the Image Up?

I've been experimenting with creating a grid layout where the bottom image will move up until it is 10px away from the image directly above it. However, no matter what I attempt, the spacing seems to be based on the tallest image rather than the one a ...

Sending data from a JSP page to a JavaScript function

I am working on a script that dynamically adds text boxes based on a specific time interval. <script type="text/javascript> $(document).ready(function() { var data = $('#data').val(); var counter = 1; var d = new Date(); va ...

Updating elements within a subarray in JavaScript can easily be accomplished by accessing the

I need help updating nested array elements in JavaScript. I want to convert dates into a different format. How can I update the nested elements? array1 = [ { "week": [ "2019-05-06T16:00:00.000Z", "2019-05-07T16:00:00.000Z", "2019-05-08T16:00:00.000Z", "20 ...

Adjusting the settimeout delay time during its execution

Is there a way to adjust the setTimeout delay time while it is already running? I tried using debounceTime() as an alternative, but I would like to modify the existing delay time instead of creating a new one. In the code snippet provided, the delay is se ...

Multiple requests were made by Ajax

I am facing an issue with my ajax code where it is being called multiple times. Below is my php code: (While loop extracts results from a database. For brevity, I have included just the modal and dropdown menu sections.) $rezPet = mysqli_query($kon, "SEL ...

Troubleshooting PhantomJS hanging with WebdriverJS tests on Windows

I am currently using webdriverjs to run automated tests on a Windows 8 system. The tests run successfully when the browser is set to Chrome, but encounter issues when I switch to PhantomJS. Interestingly, the same tests run smoothly on OS X Mavericks. Ins ...

Using jQuery to create clickable URLs within a rollover div

I am looking to have the div appear on a mouse over effect in the following code. Is there a way for me to input a url based on the data that is passed to it? Anchorage: ["Anchorage", "(555)555-5555"], (This represents the data being posted) AtlanticCit ...

Using a custom TypeScript wrapper for Next.js GetServerSideProps

I developed a wrapper for the SSR function GetServerSideProps to minimize redundancy. However, I am facing challenges in correctly typing it with TypeScript. Here is the wrapper: type WithSessionType = <T extends {}>( callback: GetServerSideProps&l ...

Is it possible to submit a select menu without using a submit button within a loop?

I'm having an issue with my code that submits a form when an option in a select box is clicked. The problem arises when I try to put it inside a loop, as it stops working. Can anyone assist me with this? Below is the code snippet causing trouble: &l ...

Invoking a PHP function within a JavaScript file

I'm facing an issue with calling a PHP function from JavaScript. I have written a code snippet where the PHP function should print the arguments it receives, but for some reason, I am not getting any output when running this code on Google Chrome. Can ...

Changing the Color of an Object3D Mesh in Three.js

Seeking advice on how to update the color of a Three.js Object3D. Initially created using MeshStandardMaterial, this object is later retrieved from the scene by its ID. Is it possible to change the color of the Mesh at this stage? If needing to replace th ...

Encountering an issue with the node.js express server when fetching data

I'm running into an issue with the fetch function and node.js. When a button is clicked on my frontend, I want to send a post request to receive an array from my backend as a response. My backend is built using node.js with express, and I'm using ...

Angular 4 Operator for adding elements to the front of an array and returning the updated array

I am searching for a solution in TypeScript that adds an element to the beginning of an array and returns the updated array. I am working with Angular and Redux, trying to write a reducer function that requires this specific functionality. Using unshift ...

Scrollbar width does not expand when hovered over

I am having trouble increasing the width of the scrollbar when hovering over it. However, I keep receiving an error in the console stating that 'scrollbar.addEventListener' is not a function. JAVASCRIPT setTimeout(function() { const scrollbar ...

Implementing a button callback function using Aurelia binding

Is there a way to pass an array of custom button objects to a specific element? Here's an example: <my-component header="My Title" buttons.bind="[{icon: 'fa-plus', display: 'New', action: onNew}]"> </my-component> ...

Choosing an option from a dropdown menu in Google Forms using Puppeteer in NodeJS

Hey everyone, I've been working on automating a Google form and I'm facing an issue with a dropdown menu. I'm struggling to select the desired value from the dropdown list. When I use Puppeteer to type in "United space Kingdom," it autocomp ...

Removing jQuery error label from an HTML block

I need a single command that will remove an error label from my HTML when the field content is changed. It currently works on input and select elements, but not within an input-group. I am looking for a solution that will work universally across all instan ...