Home > Software engineering >  finding random element in array not working
finding random element in array not working

Time:11-07

I hope you are all doing well.

I am trying to display a random fact whenever you load the website, and so far I've had no luck. The way it works is it sets a variable to a random number, then the text to the element in the array that corresponds to that number

      <p id="sciencefact">

      <script>
        var factnumber = Math.floor(Math.random() * 3);
        console.log(factnumber);

        const facts = new Array["Dead skin cells are commonly found in household dust", "The bumblebee bat is the world’s smallest mammal, weighing .05-.07 ounces", "There is parts of Africa in all four hemispheres", "The Phillipines is made of 7,641 islands"];

document.getElementById("sciencefact").innerText = facts[factnumber];

      </script>

I get a type error stating the the array is not a constructor.

CodePudding user response:

if you want to use array constructor, you should use 'new Array()' :


  <body>
    <p id="sciencefact"></p>
  </body>
  <script>
    var factnumber = Math.floor(Math.random() * 3);
    console.log(factnumber);

    const facts = new Array (
      "Dead skin cells are commonly found in household dust",
      "The bumblebee bat is the world’s smallest mammal, weighing .05-.07 ounces",
      "There is parts of Africa in all four hemispheres",
      "The Phillipines is made of 7,641 islands",
    );
    document.getElementById("sciencefact").innerText = facts[factnumber];
  </script>

CodePudding user response:

You either instantiate an Array using the Array constructor:

const facts = new Array(1, 2, 3) // just a data sample. Also parenthesis are used and not brackets.

Or simply use the Array's literal notation:

const facts = [1, 2, 3] // just a data sample

And here's a live demo:

const facts = [
  "Dead skin cells are commonly found in household dust",
  "The bumblebee bat is the world’s smallest mammal, weighing .05-.07 ounces",
  "There is parts of Africa in all four hemispheres",
  "The Phillipines is made of 7,641 islands"
];

document.getElementById("sciencefact").innerText = facts[Math.floor(Math.random() * 3)];
<p id="sciencefact"></p>

CodePudding user response:

Or you can simply initialize the array as follows too.

const facts = ["Dead skin cells are commonly found in household dust", "The bumblebee bat is the world’s smallest mammal, weighing .05-.07 ounces", "There are parts of Africa in all four hemispheres", "The Philippines is made of 7,641 islands"];
  • Related