0

I have an array like var test:Array = new Array("a", "b", "c"); How can I write a method to get one element and make it be string each time when I call this method. i.e when I call the method, it should return only 'a' and next time return only 'b' and so on.

2 Answers 2

3

You can use function shift of Array,here is a link about the function array shift

var test:Array = new Array("a", "b", "c"); 
var firstLetter:String = test.shift();//"a"
var secondLetter:String = test.shift();//"b"
var thirdLetter:String = test.shift();//"c"
Sign up to request clarification or add additional context in comments.

Comments

1

@Pan's answer is correct, but I feel the need to flag the fact that shift() ignites an extremely slow process of re-indexing your entire array. It's not something you need to concern yourself with with small arrays like in your example, but for larger arrays there's a significant performance boost if you reverse() the array first and then use pop(). I'll create a performance comparison below.

Set up our test arrays:

var shiftCopy:Array = [];
var popCopy:Array = [];

for(var i:int = 0; i < 100000; i++)
{
    var rand:Number = Math.random() * i;

    shiftCopy.push('a' + rand);
    popCopy.push('a' + rand);
}

Run the tests:

// Using shift.
var t:int = getTimer();
while(shiftCopy.length > 0) shiftCopy.shift();
trace(getTimer() - t);


// Using reverse and pop.
t = getTimer();
popCopy.reverse();
while(popCopy.length > 0) popCopy.pop();
trace(getTimer() - t);

My results:

shift:  1651ms
pop:    19ms

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.