簡體   English   中英

嘗試使用輸入的值打印出Javascript數組

[英]Trying to make a Javascript Array Print out using Inputted value

我的第一個問題是我是否可以正確地從id“ textOne”中獲取值到我的var中? 其次,我應該讓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>如果您不這樣做,人們不喜歡這里的家庭作業問題,因為完全回答並不能幫助您學習。 我會部分回答。

  1. 您不需要遍歷數組來查找值。
  2. 您可以更輕松地初始化數組。 [“薩博”,“沃爾沃”,...]
  3. 您可以引用數組中的位置,就像Saab一樣,因為它是零索引的錯誤[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   
}

雖然不完美或未經檢查,但是應該為您提供一些指示。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM