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

Is there a way to direct to a particular section of an external website without relying on an id attribute in the anchor tag?

I am aware that you can link to specific id attributes by using the following code: <a href="http://www.external-website.com/page#some-id">Link</a> However, what if the external HTML document does not have any ids to target? It seems odd tha ...

Show User-Specific Information Using DataTable

After conducting extensive research, I have been unable to find a suitable example to reference. My goal is to customize my DataTable so that it only displays data relevant to the currently logged-in user (admin accounts will have access to all data). I am ...

Incorporating an array of JSON into a Mongoose schema in JavaScript

I am currently developing an Android App focused on baseball, and I have decided to use MongoDB to store my data. The format in which I would like my JSON data stored in the database is as follows: {"<a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Troubleshooting three.js problem: Unexpected application malfunction in Chrome due to outdated code incompatible with the latest three.js library

Several weeks ago, my three.js (R48) applications were running smoothly until I encountered issues with Chrome where they no longer work. Here are the initial error messages I received: WebGL: INVALID_OPERATION: getAttribLocation: program not linked skyW ...

Executing a series of HTTP requests sequentially using Angular 5

I need some guidance on sending an array of HTTP requests in sequential order within my application. Here are the details: Application Entities : Location - an entity with attributes: FanZone fanZone, and List<LocationAdministrator> locationAdmins ...

React Href is not functioning as expected in relative paths

Recently, I delved into React apps and managed to create one with a router. Everything was smooth sailing in dev mode until I tried running index.html from the build folder after npm run build. It seems like all the href links are broken. I suspect somethi ...

Retrieving data from a textbox using JavaScript within an Excel VBA setting

I'm encountering an issue with a Macro in Excel where I need to retrieve the value of an "input type="text"" on a JavaScript webpage. However, the value is not specified in the code (value=""), and it remains unchanged even when the webpage displays t ...

What is the best way to develop shared singleton components that work seamlessly across various platforms?

How about developing a React component called LoadingMask that can toggle the display of a loading mask based on the current state? The purpose would be to show the mask before an ajax call and hide it once the data is received. To avoid showing multiple ...

Bypassing disputes in a TypeScript function

I attempted to implement the solution provided by Pacerier in response to the question about skipping arguments in a JavaScript function. However, it doesn't seem to be working for me. The function I am dealing with has numerous arguments. this.servi ...

Maintaining the active state in Bootstrap, even when manually entering a URL, is essential for smooth

Check out this fully functional plnkr example: http://plnkr.co/edit/p45udWaLov388ZB23DEA?p=preview This example includes a navigation with 2 links (routing to 2 ui-router states), and a jQuery method that ensures the active class remains on the active lin ...

using ng-show to display array elements

There is a syntax error showing up on the console for the code below, but it still functions as intended. Can someone help identify what I might be missing? <p class="light" data-ng-show="selectedAppType in ['A1','A2','A3' ...

Loop through multiple words to search in MySQL

$keywords=array("test","tset"); $matches = implode(',', $keywords); $sql = "SELECT * FROM `reg` WHERE title like in '%$matches%' group by p_title"; $data = mysql_query($sql); while($info=mysql_fetch_array($data)) { Print "{$info[&apos ...

Building a query in Javascript by utilizing object keys and values: a step-by-step guide

I am looking to transform an object with various keys and values into a query string format, for example: obj1: { abc: "Abc", id: 1, address: "something" }. The challenge is that this object is generated dynamically, so the numbe ...

Executing a function within JSX to dismiss a modal in NextJS

I am currently utilizing the Tanstack React Query library to perform a POST request from a Modal that includes a form: const addDay = (day: TDay) => { const apiURL = process.env.NEXT_PUBLIC_SERVER_URL const queryURL = apiURL + router ...

Displaying a webpage within a div section of another webpage by referencing it from a separate webpage

If I have three html pages named index.html, page1.html, and page2.html. Imagine that I am currently on page2.html and there is a list of items, each linking to different pages. Let's say one item links to page1.html. Is it feasible to load page1.ht ...

Prevent the use of exponential notation with double numbers in GWT

Is there a way to remove the exponent from a double on the client side in GWT? public double evaluate(final double leftOperand, final double rightOperand) { Double rtnValue = new Double(leftOperand * rightOperand); //Need code to remove expone ...

The "as" property in NextJS Link does not properly reload the page when opened

I recently started using NextJS and I have a question about its router. I want to link to a page, but I would like the URL to be different. <Link href="/About/About" as="/about-page"> <a> Who We Are <im ...

Utilize separate environment variables for distinct environments within a React project

Is there a secure method to externalize all environment variables, including secret keys, for a React application within a DevOps setup? Our goal is to streamline the build process across different environments, each with its own unique set of environment ...

What is the best way to retrieve data attributes from multiple div elements that share the same class name?

I have multiple div elements with the same class name. I want to extract the data attribute from these div's. I have tried some code and managed to get the result. However, I am unsure if this is the best approach for retrieving data("cartid"). Any as ...

Loop through an array containing multiple dictionaries using Swift

Trying to retrieve the titles of all the books: var error: NSError? let path = NSBundle.mainBundle().pathForResource("books", ofType: "json") let jsonData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe, error: nil) le ...