Skip to main content
Known Participant
Sep 20, 2011 7:34 PM UTC
Question

Question about random and arrays.

I want to make an array with words for example "one", "two", "three".

Then randomly choose one of the array elements and then show it in "number.text" after that, element would be deleted.

Can You give any examples please, cause I get this error all the time:TypeError: Error #1034: Type Coercion failed: cannot convert "One" to Array.

Code:

stage.addEventListener(Event.ENTER_FRAME, newWord);

function randomArrayElement(wordArray:Array):*{

          return wordArray[Math.floor(Math.random()*wordArray.length)];

function newWord (e:Event):void {

          var wordArray:Array = new Array ("One", "Two", "Three");

          var posA:Array=randomArrayElement(wordArray);

          word.text = String(posA);

This topic is closed to new replies. Start a new post to keep the conversation going.

7 replies

relaxatraja
Inspiring
Sep 21, 2011 11:57 AM UTC

To rid of the error, use the returned value as a sring:

var posA:String=randomArrayElement(wordArray);

Translate
playa_12Author
Known Participant
Sep 21, 2011 5:25 PM UTC

That solved problem with error, Thank You!

But how can I stop from running all those three words? Right now all words are running all the time, but I need that when function chooses one word from array, it stops, is there any ideas how can I achieve that goal? And when word is choosed from array it would be deleted from it.

Translate
relaxatraja
Inspiring
Sep 22, 2011 6:20 AM UTC

Here is the solution

stage.addEventListener(Event.ENTER_FRAME, newWord);

function randomArrayElement(wordArray:Array):*{

   

          itemToRemove=Math.floor(Math.random()*wordArray.length);

          return wordArray[itemToRemove];

}

var itemToRemove:int;

var wordArray:Array = new Array ("One", "Two", "Three");

function newWord (e:Event):void {

           

          var posA:String=randomArrayElement(wordArray);

          wordArray.splice(itemToRemove,1);

          if (posA==null)  stage.removeEventListener(Event.ENTER_FRAME, newWord);

          else   trace(String(posA));

}

Translate
Chris W. Griffith
Community Expert
Community Expert
Sep 20, 2011 10:34 PM UTC

Your function randomArrayElement is returning the content of the array at the random position, hence why you are getting a TypeError. You have the results being typed to the Array type.

Translate