我试图提示用户输入 1 到 5 之间的值,并根据他们输入的数字访问不同的数组索引。
<h1>JavaScript Arrays</h1>
<p>JavaScript array elements are accessed using numeric indexes (starting from 1).</p>
<h2 id="whichbar"></h2>
<script>
var chocbars = ["Mars Bar","Chokito","Boost","Crunchie","Picnic"];
var userchoice = prompt ('Please enter a value between 1 and 5');
document.getElementById("whichbar").innerHTML = chocbars[4];
</script>
我希望系统提示用户输入 1 到 5 之间的值,然后该值确定将哪 block 巧克力返回到屏幕。
最佳答案
您可以通过获取基于零的值来获取数组的索引,因此索引从零开始。
document.getElementById("whichbar").innerHTML = chocbars[userchoice - 1];
关于javascript - 如何使用数组访问不同的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57198651/