[英]Get array values and put them into different divs with a for loop?
我正在努力學習自己的javascrip + jquery,並且還嘗試正確地學習它。 因此嘗試執行DRY規則。
我發現自己遇到了一個數組問題,
var animals = [4];
一個功能
var legs = function(amount){
this.amount = amount;
this.body = Math.floor(Math.random()*amount)+1;
}
和邪惡的循環。 我也有5個div,分別稱為printAnimal1,printAnimal2等。在其中,我希望將數組中的每個值打印出來。
for(i = 0; i < animals.length; i++){
animals[i] = new legs(6);
$(".printAnimal"+i).append("animals[i]");
}
我感覺好像我接近正確的事情,但是我似乎無法弄清楚。 我也嘗試過這樣的事情:
for(i = 0; i < animals.length; i++){
animals[i] = new legs(6);
$this = $(".printAnimal");
$(this+i).append("animals[i]");
}
但是問題之一似乎是“ + i”,我無法弄清它的正面或反面。
我也知道我可以做:
$(".printAnimal1").append("animals[i]");
$(".printAnimal2").append("animals[i]");
$(".printAnimal3").append("animals[i]");
...
但這會破壞DRY規則。 嘗試使用for循環執行此操作是否全部錯誤,還是可以完成? 還是有更好的方法呢? 有人可以澄清嗎?
你的第一次嘗試應該罰款,只要你把"animals[i]"
出報價在您append()
調用( $(".printAnimal"+i).append(animals[i])
另外,我假設您聲明了var i;
在您的for循環之外? 如果不是,則需要在for循環中聲明它( for(var i=0....
)
編輯:您的小提琴的問題
startGame()
http://jsfiddle.net/SjHgh/1/是一個有效的小提琴,顯示了append()可以按您認為的方式工作。
編輯:忘記更新小提琴。 現在更正鏈接。
編輯:重新閱讀您對其他答案的答復關於您想要什么。 http://jsfiddle.net/SjHgh/3/是您想要的工作提琴。 更多說明:
new
當你叫DICE
dices[i].roll
),而不僅僅是對象 只是一些評論:
這是聲明一個只有一個項目的數組,該項目是數字4
var animals = [4];
如果仍然需要該數組,則應執行以下操作:
var animals = []; // A shiny new and empty array
然后在這樣的for循環內向其中添加項目:
animals.push(new legs(6)); //This will add a new legs object to the end of the array
另外,將其添加到div后希望顯示的內容是什么?
如果需要支路數量,應將其附加到元素(而不是支路對象直接)。
for(i = 0; i < animals.length; i++){
animals.push(new legs(6));
$(".printAnimal"+i).append(animals[i].body);
}
根據您的評論添加另一個答案
var i, dicesThrown = [];
function throwDice(){
return Math.ceil(Math.random() * 6);
}
//Throw 5 dices
for (i=0 ; i<5 ; i++){
dicesThrown.push( throwDice() );
}
//Show the results
for (i=0 ; i<5 ; i++){
$("body").append("<div>Dice " + (i+1) + ": " + dicesThrown[i] +"</div>");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.