1

我的第一个问题是我是否正确地将 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>
4

1 回答 1

0

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

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

下面的代码:

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   
}

不完美或检查,但应该为您提供一些指针。

于 2013-10-31T18:36:24.587 回答