我的第一个问题是我是否可以正确地从id“ textOne”中获取值到我的var a中?其次,我应该让while循环运行“而代表我要打印的索引值的变量”大于或等于最小数组值。我的While循环条件正确吗?

我只是基本上希望它根据1-5的用户输入在数组中打印出正确数量的索引。

提前致谢。

<input type="button" value="Click" onclick="JobDuties()" />
to see my top
<input type="text" id="textOne" />
job duties here
<p id="answer"></p>

<script type="text/javascript">

function JobDuties()
{
var x = "";
var a = document.getElementById('textOne').value;
var b = a - 1;
myduties = new Array();
myduties[0] = "Saab";
myduties[1] = "Volvo";
myduties[2] = "BMW";
myduties[3] = "Toyota";
myduties[4] = "Ford";
}
while (a>=0)
{
x = x + myduties[b];
document.getElementById("answer").innerHTML=x;
}
</script>

最佳答案

我假设您要打印出正确的数组值,而不是数组,因为没有多个。 PS>如果您不这样做,人们不喜欢这里的家庭作业问题,因为完全回答并不能帮助您学习。我会部分回答。


您不需要遍历数组来查找值。
您可以更轻松地初始化数组。
[“萨博”,“沃尔沃”,...]
您可以引用数组中的位置,就像Saab一样,因为它的索引为零
秘诀[0]
如果您要循环播放,我仍然不明白为什么要这么做。


代码如下:

var i = 1; //The variable you increment up to the use input variable a
while(i =< myduties.length){
   if(i == a){ //if i and a are same then that position
              //in the array will have the car type the user requested
      myduties[i-1] //and set it to the DOM or document element similar to what you already had
   }
   i = i + 1; //Increment i towards the one less than the length of the array
}


不完美或没有检查,但这应该为您提供一些指示。

关于javascript - 尝试使用输入的值打印出Javascript数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19713947/

10-12 00:21
查看更多