skip to Main Content

It does not work this is for an API key.

let hum = 'ethan';
let groceryList = ['bread', 'tomatoes', 'milk'];
let random = Math.floor(Math.random() * 3);
let em = '';

if (random === 0) {
  groceryList[0] === em;
}

if (random === 1) {
  groceryList[1] === em;
};

if (random === 2) {
  groceryList[2] === em;
};

if (random === 3) {
  hum === em;
}

console.log(em);

3

Answers


  1. Assignment uses a single equals sign i.e. =.

    Not sure what you are trying to achieve here, but you can reduce your multi-if block into a simple if-else.

    Use the grocery list length as a way to generate a random value.

    // Make variables immutable unless you need to reassign them
    const groceryList = ['bread', 'tomatoes', 'milk'];
    const randomIndex = Math.floor(Math.random() * groceryList.length);
    const em = '';
    
    let hum = 'ethan'; // Mutable?
    
    if (randomIndex < groceryList.length) {
      groceryList[randomIndex] = em; // Clear a random item
    } else {
      hum = em; // Should never happen, because 4 cannot be generated
    }
    
    console.log({ groceryList, hum });
    Login or Signup to reply.
  2. In JavaScript, === is a comparison operator that tests the equality of two values without performing any type conversion.

    So consider whether you really need to use the === operator in the condition.

    And when you do groceryList[1] === em;
    You are actually checking if they are equal, and not performing a placement.
    And so you need to change this to:em=groceryList[1] ;

    Login or Signup to reply.
  3. If I understood your question correctly, then you want to repeatedly randomize an array index and log the results in an array. You can do it like this:

    let groceryList = ['bread', 'tomatoes', 'milk'];
    let log = [];
    function randomize() {
        log.push(groceryList[Math.floor(Math.random() * groceryList.length)]);
        document.getElementById("log").innerText = JSON.stringify(log.join(", "));
    }
    <input id="randomize" value="randomize" onclick="randomize()" type="button">
    <div id="log"></div>

    You basically push the item of the array located at the randomized index into the log. I am also displaying it in a div for illustrative purposes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search