Home > Enterprise >  How do I convert a number to a string?
How do I convert a number to a string?

Time:05-08

I'm trying to create the rock, paper, scissors task from The Odin Project. When I run the code, the computerPlay function name shows a random number from 0-2 because of the Math.random function. How do I turn 0-2 into the choices ['rock', 'paper', 'scissors']?

let playerScore = 0;
let computerScore = 0;

const choices = ['rock', 'paper', 'scissors'];

function computerPlay() {
    let computerResult = [Math.floor(Math.random() * choices.length)];
    return computerResult;}

console.log(`Player Score: ${playerScore}`);
console.log(`Computer Score: ${computerScore}`);
console.log(computerPlay());

CodePudding user response:

Just add choices let computerResult = choices[Math.floor(Math.random() * choices.length)];

try to run the code below

let playerScore = 0;
let computerScore = 0;

const choices = ['rock', 'paper', 'scissors'];

function computerPlay() {
    let computerResult = choices[Math.floor(Math.random() * choices.length)];
    return computerResult;}

console.log(`Player Score: ${playerScore}`);
console.log(`Computer Score: ${computerScore}`);
console.log(computerPlay());

CodePudding user response:

let playerScore = 0;
let computerScore = 0;

const choices = ['rock', 'paper', 'scissors'];

function computerPlay() {
    let computerResult = [Math.floor(Math.random() * choices.length)];
    return choices[computerResult];
}

console.log(`Player Score: ${playerScore}`);
console.log(`Computer Score: ${computerScore}`);
console.log(computerPlay());

I think you mean this. The computerResult would be used as the index of the choices array. (0 => rock, 1 => paper, 2 => scissors)

So, you return the value of the array at that index.

Alternative version without passing an array index (which also works):

let playerScore = 0;
let computerScore = 0;

const choices = ['rock', 'paper', 'scissors'];

function computerPlay() {
    return choices[Math.floor(Math.random() * choices.length)];
}

console.log(`Player Score: ${playerScore}`);
console.log(`Computer Score: ${computerScore}`);
console.log(computerPlay());
  • Related