首页 > 解决方案 > 基本的 Javascript 帮助 *非常需要*

问题描述

你好我是编码新手,我需要一些关于我的 javascript 的帮助。这是我必须做的。(我希望得到一个解释和答案,我真的在努力学习。)这就是我需要做的。

我需要用它选择的随机汽车显示图像。 (选项是 bmw、Saab 和 Maserati。如果你赢得了 bmw,应该有 bmw 的图片)我不知道如何做到这一点,我从未使用过数组。

非常感谢您的帮助!

    <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>

标签: javascripthtmlcssarraysprompt

解决方案


这应该让您开始获得一辆随机的汽车并显示图像。现在你对 Chris 和 Sasha 的看法似乎是正确的(只是没有图像),试着调整这个和你的答案以继续。

// 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"/>');


推荐阅读