0

Hello I am new to coding and I need some help with my javascript. Here's what I have to do. (I'd love an explanation along with the answer, I am genuinely trying to learn.) Here is what I need to do.

I need to display an image with the random car it chooses. (the options are bmw, Saab, and Maserati. if you win a bmw, there should be a picture of a bmw) I have no idea how to do this, I never worked with arrays.

Thank you so much for any help!

    <script>

            var username = prompt("Hello, who are you?");
            var car = new Array("BMW", "Saab", "Maserati");
            console.log(car);

            if(username==="Chris") {
                document.write("<h1>Hello " + username + " you won a " + car[1] + "!</h1>");

            }else if(username === "Sasha") {
            document.write("<h1>Hello " + username + " you won a " + car[1] + "!</h1>");
            }

            else {
                document.write("<h1>Hello " + username + "!");
            }

        </script>
apsasha
  • 63
  • 1
  • 9
  • Does this answer your question? [Get random item from JavaScript array](https://stackoverflow.com/questions/5915096/get-random-item-from-javascript-array) – idmean Jan 05 '20 at 15:28

3 Answers3

1

This should get you started on getting a random car and the image to show up. Now what you have for Chris and Sasha seems to be correct (just no image), try to tweak this and your answer to continue.

// can define an array as new Array() or hard bracket syntax
var carImages = [
 // image for BMW
 'https://cdn.motor1.com/images/mgl/PR8w2/s1/bmw-serie-8-2019.jpg',
 // image for Saab
 'https://upload.wikimedia.org/wikipedia/commons/e/e5/Saab_900_GLE_%282%29_%28crop%29.jpg',
 // image for Maserati
 'https://cdn.motor1.com/images/mgl/A8Jkx/s1/maserati-granturismo-zeda.jpg',
];

// The Math.random() function returns a decimal number between 0 - 1 inclusive of 0, but not 1
// So this variable will create a number between 0 - 2. We need zero to two because the 
// zero index is the image for the BMW, 1 is for the Saab, and 2 is for the Maserati.
// Arrays start at 0 for the first element in JavaScript 
var randomIntegerBetweenZeroToTwo = Math.floor(Math.random() * 3);
// display the image on the screen. The src attribute takes the URL of the image and the
// alt attribute is for screen readers or if the image did not load.
document.write('<img src=' + carImages[randomIntegerBetweenZeroToTwo] + ' alt="car"/>');

AliF50
  • 16,947
  • 1
  • 21
  • 37
0

Maybe remove the if-else statements as these statements are not fulfilling your purpose. They are assigning cars based on the name the user inputs which is not what you want. You want your program to choose a random car from the array for whoever the user is.

So to achieve that, try using the Math.random() function to generate a random number between 0 to size of your array and save that number in a variable. Use that variable to access your array.

SabU
  • 603
  • 6
  • 4
0

Others have shown you how to pick a random value from an array. That's great and common practice, but it's a little much when you use randomness a lot. randojs.com makes random stuff easy and readable. Using randojs, all you have to do to pick a random value from an array is say rando(myArray).value instead of myArray[Math.floor(Math.random() * myArray.length)] (which picks a random decimal between 0 and 1, multiplies it by the length of your array, and then rounds the result down to produce a number from 0 to one less than the length of your array- since arrays are 0-indexed in JavaScript- and then grabs the value from myArray at that index). To avoid this small bit of complexity that usually comes along with randomness in JavaScript, all you have to do to use randojs is include the following in the head tag of your HTML document:

<script src="https://randojs.com/1.0.0.js"></script>

And then you can use it in your script, like this:

var username = prompt("Hello, who are you?");

//carArrays is an array of arrays. each nested array holds a car name at index 0 and a car photo url at index 1
var carArrays = [
  ["BMW", "https://upload.wikimedia.org/wikipedia/commons/6/64/2017_BMW_340i_%28F30_LCI%29_Luxury_Line_sedan_%282018-07-30%29_01.jpg"], 
  ["Saab", "https://upload.wikimedia.org/wikipedia/commons/5/5d/Saab_9-3_Mk2_.jpg"],
  ["Maserati", "https://upload.wikimedia.org/wikipedia/commons/1/15/2018_Maserati_GranTurismo_Sport_Automatic_4.7_Front.jpg"]
];

//check usernames for Chris or Sasha, using .toLowerCase() so we can effectively ignore capitalization or the lack thereof
if(username.toLowerCase() === "chris" || username.toLowerCase() === "sasha"){
  //pick a random nested array from carArrays
  var randomCarArray = rando(carArrays).value;
 
  //and write to the page
  document.write("<h1>Hello " + username + " you won a " + randomCarArray[0] + "!</h1><img src='" + randomCarArray[1] + "'/>");
}
else{
  //just say hello
  document.write("<h1>Hello " + username + "!");
}
/*give the images a width so they're not huge*/
img{
  width:300px;
}
<script src="https://randojs.com/1.0.0.js"></script>
Aaron Plocharczyk
  • 2,776
  • 2
  • 7
  • 15