pick string1 or string2 at random in javascript

To pick a random string from two given strings in javascript, one way is to use Math.random() 方法 to generate a random number between 0 and 1, and then use conditional statements to choose which string to return based on the generated number.

Here's an example code snippet that shows how to do it:

index.tsx
// define two strings
const string1 = "hello";
const string2 = "world";

// generate a random number between 0 and 1
const randomNumber = Math.random();

// choose the string to return based on the generated number
if (randomNumber < 0.5) {
  return string1;
} else {
  return string2;
}
288 chars
14 lines

In this example, the Math.random() will generate a random number between 0 (inclusive) and 1 (exclusive). Then, the if statement will check if the generated number is less than 0.5, if this condition is true, string1 will be returned, otherwise string2 will be returned.

gistlibby LogSnag