Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    Flash




[F8] Pulling A Random Item Out Of An Array



i have an array with 50 plus items in it and i need to know how to pull out one at random and store it in an other var.

Thanks



FlashKit > Flash Help > Flash ActionScript
Posted on: 01-15-2007, 11:23 PM


View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread

How Do I Choose A Random Item From An Array?
I have an array that will be changing.
I want to be able to choose a random item.

I'm not quite sure how I would do this.
I gues it would be best to do a random choice of the array index numbers?

But that's where I;m stuck... I'm not sure how I could use the random functions in Flash.

Any help owuld be appreciated.

Thanks.


OM

Selecting A Random Item From An Array
Hey guys,
Suppose I have an array called flowers;

flowers = ["rose", "tulip", "petunia", "daffodil"];

And I want to assign a random variable from this array to a text field;

somefield.text = ????;

What should I be putting where those ???'s are?

AS2 by the way, tried 3 and it's horrible. Sorry for the poor explanation of what I'm trying to do, half asleep.

Cheers,
-Sam

Random Select An Array Item
How would i go about randomly selecting an array item?

any help appreciated
-kool

Pulling Hair Out On Random Bg's
Im working on the splash page for a site I maintain, and for some reason I can't get the flash random backgrounds to generate. The first frame shows up on the main page but not the images that go behind it. Buut, if you run the same movie from the directory the pictures are housed in, everything works perfectly. I dont' understand!!. Its just a frickin link.. why does it work in one place and not another? please advise me ultras!!!

drnkeniris

Question: Pulling Random IMG From XML File
Whats up?!

I'm running a Flash Photogallery that load the images and links from an XML file.

As of right now, I have the image gallery loading automatically from picture to picture w/o the buttons. I also have the actual image linking to a page that I specify in the XML document. The time interval between images is 10 seconds.

What I would like to do, is have the photogallery display 3 images at once in a vertical line.

Ex:

Picture1

Picture2

Picture3

I'd also like the actionscript to display the 20-30 graphics I'll be having in this gallery at random (grabbing pics from random nodes) on the three movie instances.. I'm going over the "random" syntax in my book today trying to figure this out.... but i'm on ch. 3, so i'm jumping ahead of myself here. Always liked a challenge anywaysbut I'm getting a bit lost and confused.

I'd also like the actionscript to be able to keep track of what images(nodes) it's pulled from and to not display those on the same page unless all other images have been exhausted.

Here's the code I have:

Code:
delay = 5000;
//-----------------------
function loadXML(loaded) {
if (loaded) {
xmlNode = this.firstChild;
image = [];
description = [];
total = xmlNode.childNodes.length;
for (i=0; i<total; i++) {
image[i] = xmlNode.childNodes[i].childNodes[0].firstChild.nodeValue;
description[i] = xmlNode.childNodes[i].childNodes[1].firstChild.nodeValue;
}
firstImage();
} else {
content = "file not loaded!";
}
}
xmlData = new XML();
xmlData.ignoreWhite = true;
xmlData.onLoad = loadXML;
xmlData.load("images.xml");
p = 0;
this.onEnterFrame = function() {
filesize = picture.getBytesTotal();
loaded = picture.getBytesLoaded();
preloader._visible = true;
if (loaded != filesize) {
preloader.preload_bar._xscale = 100*loaded/filesize;
} else {
preloader._visible = false;
if (picture._alpha<100) {
picture._alpha += 10;
picture.onRelease = function(){
getURL(description[p],"_blank");
}
}
};
}
function nextImage() {
if (p<(total-1)) {
p++;
if (loaded == filesize) {
picture._alpha = 0;
picture.loadMovie(image[p], 1);
desc_txt.text = description[p];
picture_num();
slideshow();
}
}
}
function prevImage() {
if (p>0) {
p--;
picture._alpha = 0;
picture.loadMovie(image[p], 1);
desc_txt.text = description[p];
picture_num();
}
}
function firstImage() {
if (loaded == filesize) {
picture._alpha = 0;
picture.loadMovie(image[0], 1);
desc_txt.text = description[0];
picture_num();
slideshow();
}
}
function slideshow() {
myInterval = setInterval(pause_slideshow, delay);
function pause_slideshow() {
clearInterval(myInterval);
if (p == (total-1)) {
p = 0;
firstImage();
} else {
nextImage();
}
}
}


I've been going over info for almost two days now trying to figure this out, and I have asked on other boards as well for some info or help... But I really don't know what I need to put in the code to make it grab them randomly...

The book i have says to layout what you want to do on paper in words first so I can better understand what I need to do. I've done that, looked up some syntax functions i thought would work, but I just don't know enough about AS yet to so I need a little push.

What I wrote down for my desc. was:
I need to count the number of picture nodes in the XML file
then I need to pull a random node from those counted nodes and display it in the pre-defined movie slip "picture".

I'm stuck there.... so any help is appreciated.

Thanks!

Pulling From One Array, Inserting Into Another
I have a loop that sets up a number of arrays:


Code:
//for however many main menu items there are...
for (i=0; i<this.numberItems; i++){

//create empty subMenu arrays
set ("subMenu" + i, new Array);
}
I also have another array called subMenus.

what i want to do is pull an element from the subMenu array and put it into subMenu1.

I cannot for the life of me figure out how to do this.

Pulling Positions Out Of An Array
Hi I have an array with some postions in it.
for example mypositions:Array = [91,78,67,56,42,30];

What I want to do is pull them out of the array and place them and make them move.Like my_mc is at 91,I want it to move to 78,then to 67,then to 56
etc.

I have done this with a switch/case statement,but need to know how to do it with an array.

Thanks if anyone can help.

Saving To Array And Pulling Out
Need some help. Trying to learn.
I have sections with questions and answers which I can get.
But, I need to save each section into new array and tally all the final scores.
The screen will show the section score of current section that was just completed
and the final score.

I know the code has lots of problems - attached.

For the total scores the dynamic text boxes var's are totalnumcorrect, totalnumIncorrect, totaluserScore.

For the section score the dynamic text boxes var's are numcorrect, totalnumIncorrect, totaluserScore.


The title changes for each section, so I using that with if statement.

Can someone help please.

Thanks








Attach Code

//final scores
var quizTitleNode=quizNode.firstChild;
title=quizTitleNode.firstChild.nodeValue;

//section scores
section[i] = new Array(numCorrect, numIncorrect, userScore);

// total score
if (quizTitleNode.firstChild.nodeValue = "Section 1: The Mountains") {
section[i] = section1;
}

else if
(quizTitleNode.firstChild.nodeValue = "section 2: The Fields") {
section[i] = section2;
}

else if
(quizTitleNode.firstChild.nodeValue = "section 3: The Rivers") {
section[i] = section3;
}


//section scores as nested arrays
sectionsArray = new Array (section1, section2, section3);

function countFinalScore() {

for(var i=0; i = sectionsArray[0].length; i++);

}

Pulling And Playing Movies In Random Order
I want to set up a fairly simple slideshow of movies. Basically, they'll all be similar, fading a photo in, pausing, then fading it out. What I'd like is for it to pull the movies at random, so the slideshow doesn't just play through exactly the same every time you open the page. Is there a way to actionscript that?

Bonus points if there's a way to set it up on two layers so that while one photo is fading out another can be fading in, and we could have each layer pause "X" number of frames before starting a new movie clip, so that they appropriately overlap. I have it in my head how it will work, I'm just not sure how to actionscript it.

Thanks for any help!!! :)

Pulling Random MovieClips With An OnMouseDown Listener
Hello all. This is pretty simple and I think I'm pretty close, but I can't seem to get this to work. Basic functionality will be that wherever you click on the stage, a random MovieClip will be displayed.

I've been out of the Flash game for a few months so I'm quite rusty. Any help is greatly appreciated.


Code:
class Main {
private var $mcRef:MovieClip;
private var $myArray01:Array;
private var $clickListener:Object;

public function Main() {
this.$mcRef.$clickListener.owner = this;
Mouse.addListener($clickListener);
this.$mcRef.$clickListener.onMouseDown = function():Void {
this.owner._x = _xmouse;
this.owner._y = _ymouse;
this.owner.randStar();
}
}

private function randStar():Void {
this.$myArray01 = new Array("star01", "star02", "star03", "star04", "star05");
var myArrayLength:Number = this.$myArray01.length;
var inRand:Number = random(myArrayLength);
this.$mcRef.attachMovie($myArray01[inRand], $myArray01[inRand]+"_2", 1);
}
}

Pulling An Array From A Text File?
Anyone know how this is done?

[CS3] Pulling Multiple Images From An Array (XML)
Actionscript 2

I have a fla set up to pull image paths from an XML and store them in an array. I have managed to get images from the array to display one at a time, but what I want to do is to pull all of the images in the array into a movie clip and line them up horizontally. I hit a wall where I don't know why my code doesn't work. Any help on my code, or an alternate solution would be great. Here's the code


Code:

//SETS UP THE LOOP AND LOOPS THROUGH THE ARRAY
for (var i = 0; i<nodeLength; i++) {

//LOADS EACH IMAGE INTO THE MOVIECLIP COVER_MC, WITH A UNIQUE INSTANCE NAME
_mp3Player.cover_mc.loadMovie(imageArray[i], "myImage"+i);

//POSITIONS EACH MOVIECLIP NEXT TO THE LAST
eval(_mp3Player.cover_mc["myImage"+i])._x = eval(_mp3Player.cover_mc["myImage"+(i-1)])._x+eval(_mp3Player.cover_mc["myImage"+i])._width;
}
I'm a little unclear about how brackets and eval work, and if I need them together. When I load the clips, only the last image in the array appears. That makes me think that they aren't getting unique name, and one image is just over writing the next.

Thanks in advance

Timeline And Pulling Content From Array
Hi,

I'm creating a timeline (see attached image below) from 1996 - 2006 with mile stones through the companies highlights in that year.


Some years have one article in them while others have 2 and some 11.
This timeline needs to be as dynamic as possible so that people can just add content to a text file and it will show up in the timeline.

I have an array with strings like this which sits in the first frame of the root:


PHP Code:



var articleLookup = new Array();

articleLookup["1996"] = "This is James";
articleLookup["1997-1"] = "This was James in 1971";
articleLookup["1997-2"] = "This was James in  Jan of 1971";
articleLookup["1997-3"] = "This was James in Feb of 1971"; 




I have two movie clips; one called timeline_mc with my dates buttons in it

and

Another mc called content_mc with a dynamic textbox called contentText_txt.

In the timeline_mc is another mc called prevNext_mc with two buttons called prev_btn and next_btn

Now I have managed to pull in the content for 1996 when I push the 1996 button but my problem comes with 1997.
It pulls in the variable 1997-1 which is cool but I need to be able to show the content for 1997-2 and 1997-3 when the next_btn is pushed and backwards if I push the prev_btn.

There is another MC in the root called highlights_mc with a text box called highlightYear_txt. I am using this to determine what year has been clicked in an if statement (this is the route I think I should be following?). This IF statement sits in a loop created by the two frames in prevNext_mc.

Here is my code on the first frame of prevNext_mc:

PHP Code:



trace(_root.highlights_mc.highlightYear_txt.text);
if (_root.highlights_mc.highlightYear_txt.text == "1998") {
    _root.articleLookup["1998-1"];
    _root.articleLookup["1998-2"];
    _root.articleLookup["1998-3"];
    this.content_mc.prevNext_mc.next_btn = function() {
        _root.content_mc.contentText_txt.text = _root.articleLookup["1998-2"];
    };





There must be a more generic way of doing this?

Thanks in advance...

Pulling My Hair Out Copying An Array
I've been working on this problem all week and its driving me crazy. I have yet to find any way of making a copy of a multidimensional array that doesn't reference back to the original data. If you modify the original data the copied version changes as well, i've tried using the apply() method, i've used slice, splice, and about 4 other possible solutions from proto.layer51.com and NONE of them work.

Because the movies and data are dynamic the only way i can access the information is through references

_root.resultTree[obj.group][obj.slide]

i'm trying to make a copy from the obj.group level of the array and place it in the top of the array stack...i've yet to succed. why is this too much to ask? =(

Pulling Info From And Object Array And Using It To AttachMovies?
I have an object array on the root level of my movie:

logoArray = new Array();
logoArray[0] = {blur:"Bloomfield0",clear:"Bloomfield1"};
logoArray[1] = {blur:"CC0",clear:"CC1"};

and I'm tring to access that info from within another movie and use it to attach a movie into another:

dmy.attachMovie(_root.logoArray[x].blur, "Logo", 1);

When I trace the info I get all the correct info back but it is not attaching the movie.
If I put in an absolute name for the 'linkage' name it works fine.

How can I get it to read the array correctly???

Problems Pulling Variables From An Array Of Objects
Hey..

I'm created a isometric tile engine and I'm having some problems. I have a multidimensional array of "Tile" objects which is declared in a seperate .as file. Each tile object has a "select" movieclip. For some reason.. I cannot retrieve the movieclip from the tile object from my main program. I get undefined not matter what..

Here is the code from the tile object that declares the "select" variable:

Code:
this.select = attachMovie("Select","Select"+j+k,depth+98);
this.select._x = mapWidth - j * 32 + rowx + pushinx;
this.select._y = sety - 3;
this.select._visible = false;

and here is the retrieve code from the main program which returns undefined:

Code:
tilesArray[0][0].tile.select._visible = true;
what am I doing wrong here?

[Flash 8] Pulling Multiple Variables From An Array
Hello, first time post at KIRUPA.com. Hope somebody here may be able to point me in the correct direction.

I have an array question as the title explains.

Here's what I would like to accomplish:

search my array for the element (say Names) for tom (name from comboBox component)
and place the other fields(i think there called...age, picture) into either dynamic text fields or load the images into a loader component.



Code:

MyArray.Array= new Array
myArr=[name:"tom", age:"32", picture:"tomspicture.jpg"]
myArr=[name:"steve", age:"50", picture:"stevespicture.jpg"]
myArr=[name:"tom", age:"60", picture:"tomspicture.jpg"]
myArr=[name:"mark", age:"32", picture:"markspicture.jpg"]

name_mc.onRelease = function () {
myName= comboBoxName.value; // collect the value stored in the combo box component and sets it to myName

// here's the problem
// I'd like to have other boxes one for imageLoader to load the image variable
// an ageDynamic_txt box that loads the age variable
// and an nameDynamic_txt box that loads all the names variable
}
Plus is there a way to place the text in the field myArr= [ ... ,description:"I like cake"]
from a .txt file? (ie... I have a file named "desc.txt" with variables (des1)(des2) can I
pull it into the field [..., description: (des(myNuM)] so that myNum loads the specific description for that person?


Code:
desDynamicText_txt.text = myDesLV.des(myNum); // this is kinda the idea.

URLRequest Math.random To Avoid Pulling From Temp File...
Hi Folks,
I am relatively new to Actionscript. Sorry for that and sorry if this has been asked many times...I did try searching.

I am doing a URLRequest and load of an external text file. All is working fine but my swf was not updating when I updated the text file and uploaded. So I search and it turns out the loader pulls from the temp internet files. Bummer. Tested this out by deleting temp files and my updated text is now up there.
I found out today that the way around this is to have the loader send out a unique request everytime by using math.random(?).
Can someone send me an example so that my swf will grab the text file (not the cache) when I update the external text file?
Thanks in advance.

relevant code:
var textLoader:URLLoader = new URLLoader();
var textReq:URLRequest = new URLRequest("external.txt");
var cssLoader:URLLoader = new URLLoader();

var scrollPercent:Number = 0;
var minScroll:Number;
var maxScroll:Number;
var targetScroll:Number = text_mc.y;
var easing:Number = 6;
var scrollAmt:Number = 15;
var scrollDirection:Number = 0;

function textLoaded(event:Event):void
{
text_mc.external_txt.htmlText = textLoader.data;
minScroll = text_mc.y;
maxScroll = minScroll - text_mc.height + mask_mc.height;
}

}

Getting _x Value Of Array Item
Hello,
I am writing a script to shift the MC's in my movie to the right and down when I run a PrintJob(since it left justifies everything). I have created an array with all my MC's and then I am looping through and adding 40 to the _x and _y values. Problem is it is not working because when I loop through "shiftPrintClips[i]._x" comes out as undefined when I trace it. Any idea why? I can trace "shiftPrintClips[i]" and the value of the MC shows fine, just not when I try to get the location. (it works when I hard code the MC name)
Thanks!!

Here's the code:

var shiftPrintClips:Array = ["top_mc", "audio_onoff_mc", "heading_txt", "indexName_mc", "narration_mc", "mediaControlOutlines_mc", "pageNumber_mc", "glossary_mc", "presentation_mask_mc", "back_mc", "glossary_btn", "index_read_mc", "print_button", "print_btn", "next_mc"];
f
or (i=0; i<shiftPrintClips.length; i++) {
shiftPrintClips[i]._x = shiftPrintClips[i]._x + 40;
shiftPrintClips[i]._y = shiftPrintClips[i]._y + 40;
trace(top_mc._x);
trace(shiftPrintClips[i]);
}

Next Item In Array
Hi guys,

I'm new to arrays so I've probably gone about this entirely wrong but here goes. I have 9 movieclips which load in images from an xml file. This I have working but what I'd like to happen is that on the click of a button each movieclip loads the next image. There could be any number of images.

This is the script I have so far, any suggestions would be great:

licenseImage_xml = new XML();
licenseImage_xml.ignoreWhite = true;
licenseImage_xml.onLoad = function(success) {
if (success) {
processImage(licenseImage_xml);
}
};

licenseImage_xml.load('custom/images.xml');
var BookList:Array = new Array();
function processImage(xmlDoc_xml) {


BookList = xmlDoc_xml.firstChild.childNodes;

_root.windowOne.empty.loadMovie(BookList[0].firstChild.firstChild.nodeValue);
_root.windowTwo.empty.loadMovie(BookList[1].firstChild.firstChild.nodeValue);
_root.windowThree.empty.loadMovie(BookList[2].firstChild.firstChild.nodeValue);
_root.windowFour.empty.loadMovie(BookList[3].firstChild.firstChild.nodeValue);
_root.windowFive.empty.loadMovie(BookList[4].firstChild.firstChild.nodeValue);
_root.windowSix.empty.loadMovie(BookList[5].firstChild.firstChild.nodeValue);
_root.windowSeven.empty.loadMovie(BookList[6].firstChild.firstChild.nodeValue);
_root.windowEight.empty.loadMovie(BookList[7].firstChild.firstChild.nodeValue);
_root.windowNine.empty.loadMovie(BookList[8].firstChild.firstChild.nodeValue);
}

Sum Up My Item In Array
below is my script,to sum up the number in my array....but the output is all the numbers in array and not the sum up numbers....

CorrectMark =correctArray[0]+correctArray[1]+correctArray[2]+ correctArray[3]+ correctArray[4];
display.text=CorrectMark;

pls help..thankx.....thousand of thankx

Making Random Choice - Not Twice The Same Item?
Dear group,

1st of all a happy new year!

gotta question about making a random choice if i have a MC with 10 frames. Frame 1 has some AS to make a random choice between 2 till 10. This loops 3 times and print results on screen.
in frame 1 i thought about using random(10)+1, but then it's possible that when going thru it again (i want to loop 4 times) it makes the same choice as one before for example.

Is there a way to make sure all results are different from each other somehow?

thanks,

choochoo

Remove Item From Array
names = Array(); // this consists of 100 dif. names.
players = Array(); //Empty

EASY PART
Now what I want to do is to randomly take 50 diffrent names
from the namesArray add them to the players array.
Thats the easy part.

HARD PART
I don't want duplicating names I want 50 unique names from the names Array.

Any thoughts out there? .

Removing Item From Array
Okay, I have an array with numbers like 1111, 2222, 3333 etc.

So if I want to make a loop and check for one of the numbers and then if the number is there I want to remove it from the array, - what is the best way of doing so??


for(f=1; f<=array.length;f++){
if (array[f]==2222){

get rid of this thing

}

}

Jubii, - I have a new array without the 2222 post...

Can anybody help me??


Regards

Godowsky

Detecting Item In Array
hi there...

I'm checking out arrays because I want to learn to use them, but also because I need to. Which means I will have to...

I've read this: http://www.flashkit.com/tutorials/A...r-582/more3.php

but it got me in a knot.

There's no problem in creating things in an array, nor in displaying it's length...

but my problem is this:
I want to write an if-function that checks wether or not an item is in my array... and I'm totally of the hook with the sintax...

friendly greetings,
robin

Action For Each Item In Array
I have an array with several number strings. The number of strings in the array always varies. I want to execute and action (the same action) for each one of those variables. I also want there to be a delay of about 1 second between each action. What is the most effiecint way to this. I am currently using a while loop and a if/then statement for a timer. It sorta works but runs VERY VERY slow. Is there a better way, or something more efficient.





Code:
function playstring(string) {
delay = 500;
i = string.split("");
trace (i);
iLength = i.length;
trace (iLength);
n = 0;
date1 = getTimer();
date2 = date1 + delay;
while (n < iLength) {
if (date1 >= date2) {
character = i[n];
trace(character);
newChar = ord(character);
newChar = "_" + newChar;
trace(newChar);
_root[newChar].gotoAndPlay(3);
n = n + 1;
date1 = getTimer();
date2 = date1 + delay;
} else {
date1 = getTimer();
}

}
}

Can't Remove Item From Array...
Hey everyone,

Right now, I'm running a function that uses a for loop to go through an entire array of objects. If the current object meets a certain condition, it is removed from the array. For some reason, it never removes the item from the array. I've tried both delete and slice... nothing works. Here's the code I've been using.


PHP Code:




for(i=0; i < givenArray.length; i++){
    // Do something to the item.
    if(givenArray[i].property > 100){
        givenArray.splice(i, 1);
        // or delete givenArray[i];
    }
    else{
        // Do something else.
    }
}







Is it because I'm cycling through the array, and so, I can't modify it? Any help is greatly appreciated!

Naming The Last Array Item?
Naming the last array item?
I've got a question about arrays, in the following AS script:
____
next_mc.onRelease = function() {
aImages[nCurrentIndex]._alpha = 0;
_root.background_mc._alpha = 0;
nCurrentIndex++;
if (aImages[currentFrame == totalFrames]) {
this.next_mc._visible = 0;
}
};

____
At the 'if' statement, you see the following:
[currentFrame == totalFrames]
Of course that doesn't work, but how to i mention:
last item of the array, so that i can say:

if (aImages[last_item_of_array]) {
// then the play button won't be usable anymore
this.next_mc.visible = 0;
// second question:
// _alpha = 0;
// the alpha-feature doesn't make the 'play button' unusable. What feature does make the 'play button' unusable?






The whole script works, except for the above mentioned:
so here is the complete script i created:

var aImages:Array = new Array(intro_mc3, one_mc, two_mc, three_mc, four_mc, five_mc, six_mc);
var nCurrentIndex:Number = 0;
next_mc.onRelease = function() {
aImages[nCurrentIndex]._alpha = 0;
_root.background_mc._alpha = 0;
nCurrentIndex++;
if (aImages[99]) {
this.next_mc._visible = 0;
}
};
prev_btn2.onRelease = function():Void {
for (var i:Number = 0; i<aImages.length; i++) {
aImages[i]._alpha = 100;
}
nCurrentIndex = 0;
};
// repeating with setInterval from left to right
function addToMask():Void {
var nDepth:Number = mcMask.getNextHighestDepth();
mcPiece = mcMask.attachMovie("maskPiece", "mcPiece"+nDepth, nDepth);
mcPiece._x = nX;
mcPiece._y = nY;
nX += mcPiece._width;
if (nX>=intro_mc3._width+mcPiece._width) {
nX = 0;
nY += mcPiece._height;
}
}
var nX:Number = 0;
var nY:Number = 0;
var mcPiece:MovieClip;
intro_mc3._width = 400;
this.createEmptyMovieClip("mcMask", this.getNextHighestDepth());
intro_mc3.setMask(mcMask);
mcMask._x = intro_mc3._x-25;
mcMask._y = intro_mc3._y;
var nStageWidth:Number = Stage.width;
var nAddMaskInterval:Number = setInterval(addToMask, 200);
updateAfterEvent();

// if you'd like to copy this script, try creating a MC to the library that links to the var movieClip: mcPiece. The self-made movieClip is then the puzzle piece size used for the puzzle AS script

Combo Box Item Array
When the combo box is changed it will add items to another combo box, i.e if africa is chosen, all the countries in africa will be listed in the second combo box.

At the moment i am manually adding in all the countries,

_root.combo1.addItem("Label", "Data");

for 60 countries that would be messy code, is there a way to do it in an array cause my advanced actionsript isnt that good.
But i will need to be able to get the data of a country out later ....

Any ideas

Please help me

Display An Array Item Only Once?
Hi All,

I've created an XML file (Sample below).


Code:
<faq>
<category>Notifications</category>
<faqno>1.1</faqno>
<question><![CDATA[Question 1.1]]></question>
<response><![CDATA[Response 1.1]]></response>
<revdate><01/01/06></revdate>
</faq>

I've loaded it into my flash movie and created an array.
I use the following code to display the array results in a dynamic text box (list). This all works, after a lot of work and much to my amazement.


Code:
list = "";
for (i=0; i<faqs.length; i++) {
list += "<br><br><b>" + faqs[i].category + "<br><br>" + faqs[i].faqno + " " + faqs[i].question + "</b><br>" + faqs[i].response + "<br><p align='right'><font size='11px'> Last Revision: " + faqs[i].revdate + "</font></p>";
}
stop();

Finally my question: Can I modify the display code in order to display the category only once until a new category is reached?

Thanks a bunch,
Debbie

Get A Substring From Item In Array
Hi,
i am reading up an array of strings from a text file.
In one part of my code I need to remove the last character from the entry.
for example when traced the entry is
John Smith 065, I want to end up with John Smith 06
please read the comments in the code for more explanation of the problem


Code:
//I loop through my array getting the value and storing it in TargetBase
TargetBase = ThumbsArray[i+1];
//TargetBase = John Smith 065 when traced
//then I try this
DirectoryName = TargetBase.substr(0, length-1);
//DirectoryName returns a blank when traced


what am I doing wrong?
is it something to do with the numbers in the string?
thanks mark

[F8] Display Array Item
hi

i am trying to display part of an array, and all i seem to get is [object,Object]

select_lv.onLoad = function(Boolean) {
for (var i:Number=0; i < this.n; i++) {
scoreInfo.push({id:this["id"+i],category:this["category"+i] });
category.text = (scoreInfo[0]);
}
}


i want to show the details of the multidimensional array scoreInfo in category.text
thanks

Remove Item From Array
I am making a game with labels on a time line kept in an array as strings:

var tokens:Array=["tokenOne","tokenTwo","tokenThree"];

When the character in my game collides with certain items, I want to delete the reference to that label on my timeline from the array. For example if he collides with tokenOne_mc, I want to delete "tokenOne" from the above array and so on. Assuming that I have something like:

character_mc.onEnterFrame=function() {
if (character_mc.hitTest(tokenOne_mc)) {
// How do I remove tokenOne
// from tokens
// and update array
// ??????
}
};

Thanks in advance -
sleepydad

How To Load First Item In Array
Hi,

I'm trying to load the first swf in my Array automatically when the flash movie starts.

Here's my code, does anyone know how to?


PHP Code:




var aImages:Array = new Array("pic01.jpg", "pic02.jpg", "pic03.jpg", "pic04.jpg");
var aButtons:Array = new Array(bHome, bProfile, bFolio, bContact);
var myLoader:Loader = new Loader();


function btnClick(evt:Event):void {
    trace(evt.target.name);
    var countButtons:Number = aButtons.length;
    var index:Number;
    for (var i:Number = 0; i<countButtons; i++) {
        if (evt.target.name == aButtons[i].name) {
            index = i;
        }
    }
    trace( aImages[index] + " Loaded");
    myLoader.load(new URLRequest(aImages[index]));
    mContainer.addChild(myLoader);
}

var countButtons:Number = aButtons.length;
for (var i:Number = 0; i<countButtons; i++) {
    aButtons[i].addEventListener(MouseEvent.CLICK, disableButtons);
    aButtons[i].addEventListener(MouseEvent.CLICK, btnClick);

    aButtons[i].mouseChildren = false;
}

function disableButtons(evt:Event):void {
    for (var i:Number = 0; i<aButtons.length; i++) {
        if (evt.target.name == aButtons[i].name) {
            trace(evt.target.name + " has been clicked");
            aButtons[i].mouseEnabled= false;
            aButtons[i].alpha = .5;
        } else {
            aButtons[i].mouseEnabled= true;
            aButtons[i].alpha = 1;
        }
    }
}

[F8] Find Next Array Item
This is probably an easy question.. If I have an array like "apples, oranges, pears, plums" and I want to find what comes after or before an item, how do I do it? For example, how would I create a button that would tell me the item that comes after (or before) "pears"?

Finding the index number of an item is easy, but how can I use it to find out what item has a higher (or lower) index number?

//find index number of "pears"
myArray = new Array('apples', 'oranges', 'pears', 'plums');
for (var i in myArray) {
if (myArray[i] == 'pears') {
arrayNum=i
break;
}
}

thanks!
Sebastian

Remove Item From An Array
I am trying to remove an item from an array.

var myArray= new Array("A","B","C","D","E","F");
delete myArray[2];//this will delete C and the output will be like this.

trace(myArray); // A,B,undefined,D,E,F

what if i dont want that "undefined" there? I want the output as A,B,C,D,E,F


thanks...

Concatinate With Array Item
Code:
for (var cnt:Number=0; cnt>=_root.onhelp.length-1; cnt++)
{
_root.onhelp[cnt]._accProps.silent = true;
}
onhelp is an array. It contains button names, one_btn, two_btn ..... etc.
I think I am concatinating it incorrectly. Anyone knows what is wrong?


Thanks...

Array Misses Off First Item ?
Hi,
When the following code runs, it works fine except that:

the 1st item from theArray is replaced by the 2nd, the 2nd is replaced by the 3rd item etc, until the last item which is 'undefined'.


Code:
setInterval(drawMenuItem, 50);
var i:Number = 0;
var theArray = new Array("menu 1", "menu 2", "menu 3, "menu 4");
function drawMenuItem():Void {
if (theArray[i].length) {
++i;
buttonMC.duplicateMovieClip("button"+i, i);
var targ = eval("button"+i);
}
if (i == 0) {
targ._y = 0;
} else {
var previousTarg = eval("button"+(i-1));
targ._y = previousTarg._y+previousTarg._height-1;
}
targ._x = 0;
targ.nmbr = +i;
targ.title = (theArray[i]);
}

can anybody please work this out?

Every Item In Array Uses Function...
Hello.

I have some arrays which contain a number of MC's. We have passed an event listener to each item in the array, and using currentTarget we have them working fine, each item runs a specific function on mouse over (thanks to the help from this forum ). Now, is there a way to make the entire collection run a function as a group?

For example, on mouse over each thing is doing what is should do on it's own, but if I press a button somewhere on the stage I want the collection as a group to say, shrink to half the group's original size (or have every individual item in the array run the same function a tht esame time).

Is that possible?

Ta, A.

Move 1st Item In An Array To The End?
What the Fastest way to move the 1st item in an Array to the end?

David

UnloadMovie Using The First Item In An Array
ok, i have an array on the main timeline called "loaders" and normally there is nothing in there until it reaches a certain frame where "photosLoader" becomes [0] in the array. i have a movie clip, and inside of that movie clip is a button that says to replace the first item in that array with "workLoader". the line of code before that tells the photosLoader to unloadMovie itself. Here is the code:


Code:
// loadMovie into workLoader
loadMovie("work/web/webMain.swf", _root.workLoader);

// unload current loadMovie in loaders array
unloadMovie("_root.loaders[0]");

// add loadMovie clip to loaders array
loaders[0] = "workLoader";
trace(loaders);
this does not work as _root.loaders[0] doesn't read the current item thats first in the loaders array that is on the main timeline. any ideas on how i can pull that first item out into the _root. command in the unloadMovie so that it unloads it?

Thanks in advance.

How Do You Get The Previous Array Item?
I'm loading data into a movie clip via XML and an array system that duplicates a single movie clip any number of times, as defined by the XML file. The code is working, but what I would like to do now is be able to get the previous number from the array.

Here's the script I'm using:

ActionScript Code:
stop();var newsXML:XML = new XML();_level0.homeMC.newsMC.newsClips.newsXML.ignoreWhite = true;_level0.homeMC.newsMC.newsClips.newsXML.load('news.xml');_level0.homeMC.newsMC.newsClips.newsXML.onLoad = function():Void  {    _level0.homeMC.newsMC.newsClips.nodeLength = this.firstChild.childNodes.length;    for (i=0; i<nodeLength; i++) {        newsPath = _level0.homeMC.newsMC.newsClips;        newsPath.newsClipping.duplicateMovieClip('newsClipping'+i, newsPath.getNextHighestDepth());        newsPath['newsClipping'+i]._y += getProperty(newsPath['newsClipping'+(i-1)], _y)+getProperty(newsPath['newsClipping'+(i-1)], _height);        newsPath['newsClipping'+i].newsTitle.text = this.childNodes[0].childNodes[i].childNodes[0].firstChild;        newsPath['newsClipping'+i].newsDate.text = this.childNodes[0].childNodes[i].childNodes[1].firstChild;        newsPath['newsClipping'+i].newsMessage.text = this.childNodes[0].childNodes[i].childNodes[2].firstChild;    }    _level0.homeMC.newsMC.newsClips.newsClipping.unloadMovie();};


The problem is on line 10 where I try to define the "_y" value for the duplicated movie clips. Since each clip is set to auto-size to fix the text content, I can't have them a set distance apart. What I'm hoping to be able to do is to have it get the "_height" and "_y" values from the previous movie clip (so if it's "newsClipping3" I want the values from "newsClipping2" and so on).

I'm new to the whole usage of arrays in scripting and this is the first time I've used this sort of script before so If anyone can tell me what I need to do or point me in the direction of a tutorial that will explain it that'd be of great help!

Time is a bit of a rush as I need this entire project done by Monday morning though... So the sooner I get an answer the better! Thanks!

How Do I Get The Key Position Of An Item In An Array?
I'm working on an XML gallery, and when you click on a thumbnail, it loads the corresponding picture. I'd like to add a forward and next button, and need to extract the key position of the current picture being displayed, so I can show the picture before or after it.

How To Load First Item In Array
Hi,

I'm trying to load the first swf in my Array automatically when the flash movie starts.

Here's my code, does anyone know how to?


ActionScript Code:
var aImages:Array = new Array("01.swf", "02.swf", "03.swf", "04.swf");var aButtons:Array = new Array(bHome, bProfile, bFolio, bContact);var myLoader:Loader = new Loader();function btnClick(evt:Event):void {    trace(evt.target.name);    var countButtons:Number = aButtons.length;    var index:Number;    for (var i:Number = 0; i<countButtons; i++) {        if (evt.target.name == aButtons[i].name) {            index = i;        }    }    trace( aImages[index] + " Loaded");    myLoader.load(new URLRequest(aImages[index]));    mContainer.addChild(myLoader);}var countButtons:Number = aButtons.length;for (var i:Number = 0; i<countButtons; i++) {    aButtons[i].addEventListener(MouseEvent.CLICK, disableButtons);    aButtons[i].addEventListener(MouseEvent.CLICK, btnClick);    aButtons[i].mouseChildren = false;}function disableButtons(evt:Event):void {    for (var i:Number = 0; i<aButtons.length; i++) {        if (evt.target.name == aButtons[i].name) {            trace(evt.target.name + " has been clicked");            aButtons[i].mouseEnabled= false;            aButtons[i].alpha = .5;        } else {            aButtons[i].mouseEnabled= true;            aButtons[i].alpha = 1;        }    }}


thanks
vxd

UnloadMovie Using The First Item In An Array
ok, i have an array on the main timeline called "loaders" and normally there is nothing in there until it reaches a certain frame where "photosLoader" becomes [0] in the array. i have a movie clip, and inside of that movie clip is a button that says to replace the first item in that array with "workLoader". the line of code before that tells the photosLoader to unloadMovie itself. Here is the code:


Code:
// loadMovie into workLoader
loadMovie("work/web/webMain.swf", _root.workLoader);

// unload current loadMovie in loaders array
unloadMovie("_root.loaders[0]");

// add loadMovie clip to loaders array
loaders[0] = "workLoader";
trace(loaders);
this does not work as _root.loaders[0] doesn't read the current item thats first in the loaders array that is on the main timeline. any ideas on how i can pull that first item out into the _root. command in the unloadMovie so that it unloads it?

Thanks in advance.

Remove All Item From Array
Hi
Is it possible to all item fron and array and keep one or two that i want.


ActionScript Code:
_global.manfListMain = new Array(pao,laz,dop,whi,ver, );


This is a small example but there is a long list of item in above array and i am looking for something like

manfListMain.delete(laz,whi)

deleting it by variable name and not by its position.

Display Next Array Item...
i've created an array of 10 items.
the text in the array items are called out by 10 specific buttons, no problem.

the trouble is that i want to create a next and previous button that just displays the next array item, no matter what the currently displayed item is.

does anyone have any suggestions?

Create Var From Array Item
Hi all.

I've an array like this:


ActionScript Code:
var SQL_DBCOLUMNS:Array = new Array("Id", "Nome", "Indirizzo", "Categoria");


And i need to create an object that contains four vars named like the array items:


ActionScript Code:
var oObject:Object = new Object();
oObject.Id = arValues.Id[i];
oObject.Nome = arValues.Nome[i];
oObject.Indirizzo = arValues.Indirizzo[i];
oObject.Categoria = arValues.Categoria[i];


But i need to do it using arrays:


ActionScript Code:
var oObject:Object = new Object();
oObject.SQL_DBCOLUMNS[0] = arValues.Id[i];
oObject.SQL_DBCOLUMNS[1] = arValues.Nome[i];
oObject.SQL_DBCOLUMNS[2] = arValues.Indirizzo[i];
oObject.SQL_DBCOLUMNS[3] = arValues.Categoria[i];


Obviously
oObject.SQL_DBCOLUMNS[0] = arValues.Id[i] doesn't works. How can I do that?

Thx to all for the help and good summer!!!

Remove An Item From Array
ok, I want to randomly choose an item from an array. ok here, I think. My question is this, how can I remove an item from the array after I get teh info out of it so that next time I call a random item from the array, I will not choose the sam eone again? thanks-
Aaron

Copyright © 2005-08 www.BigResource.com, All rights reserved