2010-12-22 148 views
0

如何在flash中創建一個數組as2,並從那裏選擇12個值將它們分配給十二個不同的變量?AS2數組隨機選擇

到目前爲止,我得到這個:

quotes = new Array(); 


quotes[0] = "one"; 
quotes[1] = "two"; 
quotes[2] = "three"; 
quotes[3] = "four"; 
quotes[4] = "five"; 
quotes[5] = "six"; 
quotes[6] = "seven"; 
quotes[7] = "eight"; 
quotes[8] = "nine"; 
quotes[9] = "ten"; 
quotes[10] = "eleven"; 
quotes[11] = "twelve"; 
quotes[12] = "thirteen"; 
quotes[13] = "fourteen"; 
quotes[14] = "fifteen"; 
quotes[15] = "sixteen"; 
quotes[16] = "seventeen"; 
quotes[17] = "eighteen"; 
quotes[18] = "nineteen"; 
quotes[19] = "twenty"; 

進出口保持這種結構,因爲它會更容易從長遠來看,保持並有更多的可讀性。

我不知道的是如何從中取出12個隨機值並將它們分配給變量。

好了,現在我已經加入這片:

trace(quotes) 
for(var i:Number = 0; i<12; i++){ 
      var x:Number = Math.floor((Math.random()*quotes.length)); 
      trace("X :: " + x); 
      trace("ARRAY VALUE :: " + quotes[x]); 
      quotes.splice(x,1);   
    } 

現在我看到在跟蹤12個不同的值,而無需重複。 但我仍然不知道如何使結果成爲12個不同變量的值。

+0

`quotes [19] =「twenty」;`,也許? – 2010-12-22 13:15:31

+0

upsie,小錯誤。 – Lopez 2010-12-22 13:17:23

回答

1
var myArray = quotes.slice(); // make a copy so that the original is not altered // 
n = 12; 
for (var i:Number = 0; i < n; i++) { 
    var randomSelection = Math.floor((Math.random() * myArray.length)); 
    trace("Selected: " + myArray[randomSelection]); 
    myArray.splice(randomSelection, 1); 
} 

無恥地從隨機論壇採取和改編。

0

Math.random返回一個範圍在[0-1]範圍內的數字,這意味着它永遠不會實際返回1,因此,由於您需要將值設置爲n + 1,其中n是真正的上限。

現在,瞭解更多關於您要使用的變量的外觀以及它們是否屬於同一個對象將會很好。我將繼續並假設變量不是按順序命名的(即prop1,prop2,prop3等),但它們將同時設置。

因此,一個的解決辦法是:

// Store the variable names 
var properties = [ 
    "firstProperty", 
    "secondProperty", 
    "propertyThree", 
    "prop4", 
    "prop5", 
    "prop6", 
    "seventhProp", 
    "prop8", 
    "prop9", 
    "propTen", 
    "propEleven", 
    "property12" 
]; 

var selection = quotes.slice(); // make a copy so that the original is not altered // 

for (var i:Number = 0; i < properties.length; i++) 
{ 
    var randomIndex = Math.floor(Math.random() * (selection.length + 1)); 

    // target is the object that holds the properties 
    target[properties[i]] = selection.splice(randomIndex, 1); 
} 

這裏做的另一種方式,即允許對不同的對象設置屬性:

var i = 0; 
var randomQuotes = quotes.sort(function() 
{ 
    return Math.round(Math.random() * 2) - 1; 
}); 

target.prop = randomQuotes[i++]; 
target.prop2 = randomQuotes[i++]; 
other.prop = randomQuotes[i++]; 

// Keep going for all the properties you need to set 

這可以被抽象掉成RandomQuote類,使您可以重新使用該功能。