Skip to main content
Known Participant
September 20, 2011
Question

Question about random and arrays.

  • September 20, 2011
  • 2 replies
  • 968 views

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 has been closed for replies.

2 replies

relaxatraja
Inspiring
September 21, 2011

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

var posA:String=randomArrayElement(wordArray);

playa_12Author
Known Participant
September 21, 2011

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.

relaxatraja
Inspiring
September 22, 2011

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));

}

Chris W. Griffith
Community Expert
Community Expert
September 20, 2011

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.