javascript - 基本的 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>
解决方案
这应该让您开始获得一辆随机的汽车并显示图像。现在你对 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"/>');
推荐阅读
- python - 没有自我访问类属性的困惑 - python
- mongodb - 如何在这个 mongodb 聚合函数中下订单
- python-3.x - 当输入错误时,程序的第一部分不会使用户重新输入输入
- typescript - 为 TypeScript 文件禁用 ESLint
- python - 使用 tf.GradientTape() 训练逻辑回归无法收敛
- html - 如何将 HTML 代码与 CSS 等 Ext JS 代码分开?
- debugging - 如何在插入之前获取.ko模块的加载地址?
- node.js - rados_clone_range返回的-95错误码是什么意思?
- scala - 等到主管准备好再执行测试
- azure - 使用 Azure 通过 URL 呈现 MP3 文件