MNOPYZ
MNOPYZ

Reputation: 55

AS3 putting each element of an array on a separate line

I'm working on a game which contains the following code; what it's meant to do is pick 8 random names from an array and enter them into some text onscreen, so that each element is on a separate line. Here's the summary of my code:

var a:Array
for (var i:Number=1; i<=packQ; i++)
{
shuffle(packShuffler);
//Note: this function randomly reorganizes the array "packShuffler", it's a pretty complicated function so lets leave it at that.
a.push(packShuffler[0])
a.push(packShuffler[1])
a.push(packShuffler[2])
a.push(packShuffler[3])
a.push(packShuffler[4])
a.push(packShuffler[5])
a.push(packShuffler[6])
a.push(packShuffler[7])
}
cardGet.text=""+a

//textbox looks something like this:
//blue,white,dragon,beast,great,black,Sword,Circle

I know it looks very very awkward, especially the push part, but it's the only way I know at the moment :/

Well, my problem is, at the last line {cardGet.text=""+a}, the text appears as a big block of elements with commas between them, what I want is to make each element appear on a separate line. How do I do this?

Upvotes: 0

Views: 90

Answers (1)

Panzercrisis
Panzercrisis

Reputation: 4750

Part of the problem is that a.toString() is getting called implicitly, on the line that says cardGet.text=""+a. That being said, an Array's toString() method will, by definition, return element1 + ", " + element2 + ", " + ... + elementn.

But why are you pushing them onto a new array? Why not simply shuffle the old one, as you have, and then just build your own string out of it? Kind of like this:

shuffle(packShuffler);
cardGet.text = "";

// takes every element, except for the last, and adds it and a newline
// to the string
for (var j:int = 0; j < packShuffler.length - 1; j++)
{
    cardGet.text += packShuffler[j] + "\n";
}

// adds the very last element to the string without a newline
cardGet.text += packShuffler[packShuffler.length - 1];

Upvotes: 1

Related Questions