Kusa Shaha
Kusa Shaha

Reputation: 112

How to add numbers in array via a loop in AS3?

var arr: Array = [1, 2, 3, 4, 5, 6, 7, 8, 9];

I can add these numbers to an array separately like this but how do I add 1 to 50 at once instead of typing it all the way through?

for (var i:Number=1; i<=50;i++){
var arr:Array(i) = [i];
}

function randomize(a: * , b: * ): int {
    return (Math.random() > .5) ? 1 : -1;
}

trace(arr.sort(randomize));

I am trying to implement something like this. Thank you.

Upvotes: 1

Views: 77

Answers (1)

Organis
Organis

Reputation: 7316

Pretty simple. You can address the Array's elements via square bracket notation. Works both ways:

// Assign 1 to 10-th element of Array A.
A[10] = 1;

// Output the 10-th element of A.
trace(A[10]);

Furthermore, you don't even need to allocate elements in advance, Flash Player will automatically adjust the length of the Array:

// Declare the Array variable.
var A:Array;

// Initialize the Array. You cannot work with Array before you initialize it.
A = new Array;

// Assign some random elements.
A[0] = 1;
A[3] = 2;

// This will create the following A = [1, null, null, 2]

So, your script is about right:

// Initialize the Array.
var arr:Array = new Array;

// Iterate from 1 to 50.
for (var i:int = 1; i <= 50; i++)
{
    // Assign i as a value to the i-th element.
    arr[i] = i;
}

Just keep in mind that Arrays are 0-based, so if you forget about index 0 it will remain unset (it will be null).

Upvotes: 2

Related Questions