AS3 How to make a kind of array that index things based on a object? but not being strict like dictionary - actionscript-3

How to make a kind of array that index things based on a object? but not being strict like dictionary.
What I mean:
var a:Object = {a:3};
var b:Object = {a:3};
var dict:Dictionary = new Dictionary();
dict[a] = 'value for a';
// now I want to get the value for the last assignment
var value = dict[b];
// value doesn't exits :s
How to make something like that. TO not be to heavy as a lot of data will be flowing there.
I have an idea to use the toString() method but I would have to make custom classes.. I would like something fast..

Why not make a special class that encapsulates an array, put methods in there to add and remove elements from the array, and then you could make a special method (maybe getValueByObject(), whatever makes sense). Then you could do:
var mySpecialArrayClass:MySpecialArrayClass = MySpecialArrayClass();
var a:Object = {a:3};
var b:Object = {a:3};
mySpecialArrayClass.addElement(a,'value for a');
var value = mySpecialArrayClass.getValueByObject(a);
I could probably cook up a simple example of such a class if you don't follow.
Update:
Would something like this help?
http://snipplr.com/view/6494/action-script-to-string-serialization-and-deserialization/
Update:
Could you use the === functionality? if you say
if ( object === object )
it compares the underlying memory address to see if two objects are the same reference...

Related

trying to get properties of objects inside object properties

Sometimes JavaScript is playing with me (although the deal was that I would be playing with it...) This test code below keeps resisting so I'm looking for a little help from more clever people around here.
Answering to a recent question I tried to create a readable list of all the color IDs useable in Google Advanced Calendar API.
The request is very simple : Calendar.Colors.get()
The response is an object with a couple of properties, each one being other objects with other properties.
I can go down to the second level but the last -and most useful in this case - level returns a disturbing "undefined" (see partial log below)
And that's my question...
code with comments :
function getColorList(){
var colors = Calendar.Colors.get();
//Logger.log(JSON.stringify(colors));
for(var cat in colors){
Logger.log("category "+cat+" = "+JSON.stringify(colors[cat])+'\n\n')
}
// from there I try the "event" category
var events = colors["event"];
Logger.log('object colors["event"] = '+ JSON.stringify(events))
// then I try to get every properties in this object
for(var val in events){
Logger.log("key "+val+" = "+JSON.stringify(events[val]))
}
}
Full log is viewable here (externalized to keep this reasonably short)
Looks like (key) may be indicating a read-only definition as Sandy was eluding to.
Just make your own object from colors to loop through after converting it to string:
var json = JSON.stringify(colors["event"]);
var myObj = JSON.parse(json);
for(var val in myObj){
Logger.log("key "+ val +" = "+JSON.stringify(myObj[val]))
}

Using objects instead of arrays

I've spent nearly 1 week to learn working with objects instead of arrays. I had thought it was easy to call them and created some objects and set their properties. However I can't access them now, I tried this:
function onBoxClick(event:MouseEvent):void {
var str:String = event.currentTarget.name;
trace(str);
str = str.substring(str.indexOf("_") + 1);
trace(getChildByName("copy_" + str)); // trying to trace an object by name
}
My question is if there's a practical way of dealing with objects, otherwise what's the purpose of using them.
Edit: Here's my function that I use to create movieclips and other things:
function addBoxes(isUpdate:Boolean):void {
var copyOne:Object = getReadOnlyValues();
copyOne.name = "copy_" + num;
// Set default mc1 settings
var settings1:Object = copyOne.mc1Settings;
for(var num2:String in settings1) {
copyOne.mc1[num2] = settings1[num2];
}
// Set default mc1text settings
var settings2:Object = copyOne.mc1TextSettings;
for(var num3:String in settings2) {
copyOne.mc1Text[num3] = settings2[num3];
}
copyOne.mc1.x = nextXpos;
copyOne.mc1.name = "captionBox_" + num;
addChild(copyOne.mc1);
copyOne.mc1.addEventListener(MouseEvent.CLICK, onCaptionClick);
copyOne.mc1Text.name = "captionBoxText_" + num;
copyOne.mc1.addChild(copyOne.mc1Text);
// ---------------------------------------------------------------
// Set default mc2 settings
var settings4:Object = copyOne.mc2Settings;
for(var num4:String in settings4) {
copyOne.mc2[num4] = settings4[num4];
}
// Set default mc2text settings
var settings5:Object = copyOne.mc2TextSettings;
for(var num5:String in settings5) {
copyOne.mc2Text[num5] = settings5[num5];
}
copyOne.mc2.x = nextXpos;
copyOne.mc2.y = copyOne.mc1.height;
copyOne.mc2.name = "box2_" + num;
addChild(copyOne.mc2);
copyOne.mc2Text.name = "box2BoxText_" + num;
copyOne.mc2.addChild(copyOne.mc2Text);
copyOne.mc2.addEventListener(MouseEvent.CLICK, onBoxClick);
if (num / subunits is int) {
trace (num);
// createMc("normalBox", true);
}
nextXpos = nextXpos + copyOne.mc2.width;
// traceObj(copyOne);
// traceObj(getReadOnlyValues());
}
I called this function in a loop so I created many movieclips. Now I can't access objects' properties and their childen (e.g textfield).
Objects I have on stage: Movieclips and textfields
Where they come from: The function above
What I'm trying to do with them: Tracing movieclips and textfields (that are holded by objects) to change their children (textfield) text
What happens instead of what I expect: Trace code outputs undefined instead of giving me object type trace(getChildByName("copy_" + str)); // trying to trace an object by name
Is there a practical way of accessing an object whose name is "copy_1" and its property whose name is "box2_1" (movieclip)?
One problem I see is the "copyOne" object has been created within the scope of "addBoxes", so it will no longer exist outside of this function.
Another is you're trying to access an Object via getChildByName, which only addresses displayObjects of the displayObjectContainer you are calling from.
If you want to loosely keep track of variables with things like Objects or MovieClips (which are both dynamic-style objects that let you add properties to them as you wish), just use MovieClips to house your values. The movieClips, being on the stage, will be retained in memory until removed from the displayList (stage).
Also, check out the Dictionary, a sort of key/value based way of storing collections of objects.
Better yet, if you use strongly-typed custom objects (creating your own classes to extend MCs, and adding your own public or private methods and values), there are benefits such as using Vectors (fancy, fast arrays that are compatible with any Object type you choose).
I don't really know if I understood your question or not, but as #ozmachine said in his answer, you can not use getChildByName, instead I think that you can take a look on this, may be it can help :
var container:DisplayObjectContainer = this;
function getReadOnlyValues():Object {
return {
mc1: new box(),
mc1: {
name: 'mc1_',
alpha: 1,
x: 0,
y: 0,
width: 30,
height: 25
},
mc1Text: new TextField(),
mc1Text: {
text: 'test',
x: 0,
y: 0,
selectable: false,
multiline: false,
wordWrap: false
}
}
};
// create 5 objects
for(var i=0; i<5; i++){
container['copy_'+i] = getReadOnlyValues();
var obj:Object = getObjectByName('copy_'+i);
obj.mc1.alpha = 1;
obj.mc1.x = 0;
obj.mc1.y = 50 * i;
obj.mc1.width = 100;
obj.mc1.addChild(obj.mc1Text);
obj.mc1Text.text = 'test_' + i;
addChild(obj.mc1);
}
// get object by name
function getObjectByName(name:String):Object {
return container[name];
}
// change the text of the 4th button
stage.addEventListener(MouseEvent.CLICK, function(e:MouseEvent):void {
var obj:Object = getObjectByName('copy_3');
obj.mc1Text.text = 'new text';
})
Array and Object are both data structures.
Data means some form of information.
Data structure means some form of information being stored in a certain way.
Array and Object are two different ways to store information.
Arrays identify data with integer numbers.
An integer number to identify a single element of an array is called an index
Arrays are ideal to represent a list of similar things that belong to each other.
var names:Array = ["John", "Paul", "George", "Ringo"];
This often means that the elements of an array are of the same type, like in the example above.
But they don't have to:
var numbers:Array = [42, "twenty-five", "XIIV"];
For the above examples it's easy to answer the questions "What are the names of the four beatles?", "What different representations of numbers did you stumble upon during your trip through the historic town?". Other questions are harder or impossible to answer. "What Roman numerals did you stumble upon in the historic town?"
Objects identify data with names.
A name to identify a single element of an object is called a property
Objects are ideal to represent a list of dissimilar things that belong to each other.
var paula:Object = {age:37, name:"Paula", hairColor:0x123456};
This often means that the elements of an object are of different type, like in the example above.
But they don't have to:
var car:Object = {manufacturer:"Porsche", color:"red", sound:"wroooooom", soundOfDriver:"weeeeeeeeeeee"};
Considering this, let's take a look at your code and see how it applies.
The big picture is that you have a function addBoxes that you call multiple times. As one function should have one purpose, this function will do something similar every time it is executed. Uh-Oh: "similar". Whatever the result of this function is, it should go into an array. Each call to that function would be an element of the array. You can see this clearly on your use of "num" to identify whatever is happening in your current run of the function.
What data is present in your function?
copyOne
mc1
mc1Text
mc2
mc2Text
copyOne is a troublemaker here and what causes your confusion. It's trying to do everything at once and therefore you are not able to think clearly about when to use a Array and when Object. One would call it a god object. And that's not a good object to have around.
Your choice for variable names is very bad.
You choose super generic names like "mcX" only to later add a name property to it that describes what it truly is.
But even that doesn't hold true for whatever "Box2" is supposed to be.
Choose names so that it'S easy to understand what something in your code is.
It looks like you created all or parts of this structure jsut for this question and therefore lacked meaningful names.
I highly recommend that you do not learn by such made up projects. But from the real world.
I will therefore impose the following goal:
mc1 and mc1Text represent a caption
mc2 and mc2Text represent a content
With all this, I ask again:
What data is present in your function?
captionBox
captionText
contentBox
contentText
Both caption and content consist of a box and a text.
These are different things, so caption and content are each an object with properties "box" and "text"
One could think that due to this similarity, they both should go into an array.
But I beg to differ. A caption and a text are not the same thing. You deal with captions and texts differently. Walking on the streets you might catch a big caption in the news quickly, but not a lengthy text. That's why each of them should be a property of the object that's created in the function.
Here's somewhat of a conclusion:
var allBoxes:Array = []; // array to store the similar results of every function call
function createBoxes():void
{
var boxes:Object = {};
//the box consists of caption & content, both bying of the same type, but are containing different data
boxes.caption = {box:{}, text:{}}; //caption
boxes.content = {box:{}, text:{}}; //content
allBoxes.push(boxes);
}
This is it. That's how and why I would model your data with objects and arrays.
But it doesn't end here. My conclusion lacks a lot of the code you posted.
While the above is mostly language independent, the missing code is specific to Actionscript and not just on how to model data. It's as follows...
As3 is object oriented.
This is good, because the above conclusion has a lot of objects in it.
To define how some object is/does/moves/farts/etc, one creates classes.
The following changes take place (for reasons out of the scope of this answer):
createBoxes (formerly known as addBoxes) calls the constructor of
a class "CaptionAndContent" that extends Sprite.
There's no more need to explicitely create an object "boxes" as the constructor does exactly that.
The caption and content will not have a property "box", because
they can be the box themselves. This is exactly how it's done in the
code of the question. The default settings are set in the constructors of their classes.
Here's reduced snippet of code that hopefully illustrates how the classes could look like.
Each class should be in its own file, with the necessary imports, package block and the additional functionality that you did not specify in your question.
public class CaptionAndContent extends Sprite
{
private var caption:Caption;
private var content:Content;
public function CaptionAndContent(captionText:String = "", contentText:String = "")
{
caption = new Caption(captionText);
addChild(caption);
content = new Content(contentText);
content.y = caption.height;
addChild(content);
}
}
public class ClickableBoxWithText extends Sprite
{
protected var textField:TextField;
public function ClickableBoxWithText(text:String = "")
{
textField = new TextField();
textField.text = text;
addChild(textField);
addEventListener(MouseEvent.CLICK, onClick);
}
protected function onClick(mouseEvent:MouseEvent):void
{
//override this in a sublclass
}
}
public class Caption extends ClickableBoxWithText
{
public function Caption(text:String = "")
{
super(text);
// apply all the default settings of caption here.
}
}
public class Content extends ClickableBoxWithText
{
public function Content(text:String = "")
{
super(text);
// apply all the default settings of content here.
}
}
Using them would look something like this:
var allBoxes:Array = []; // array to store the similar results of every function call
function createBoxes():void
{
var captionAndContent:CaptionAndContent = new CaptionAndContent("This is the caption...", "...for this content");
captionAndContent.x = nextXpos;
addChild(captionAndContent);
allBoxes.push(captionAndContent);
}
Last but not least, the identification problem in the click handler.
Your question already contains the answer:
event.currentTarget
That's the reference to the object that was clicked on.
In my code it would be
mouseEvent.currentTarget
This identifies the object already. It's pointless to look up one of its properties (its name for example) in order to search all the objects for that name, just to identify the same object that you already had to identify (without a name) in order to get the name.
You aren't identifying the objects by name anyway. What differs between the names and what supposedly makes them unique is a number at their end. As pointed out in this answer, this is what's called an index and the thing you are trying to identify with it should go into an array. In my example codes, this is allBoxes.

AS3 - getting variable named in order within a function

I am sorry if this is a beginner's question.
I made some Arrays named like map01, map02 and so on... As you can see, I'm making a tile-based flash here. And I need to make a function that when you input a number like: createmap(1); it will get the variable map01 and use the information.
Can I do anything like: var temp:Array = Array(["map" + valueInput]);??
Please tell me if you need anything more.
First, instead of having variables with indices in their names, you should create an array of them. Here, an array of arrays.
So you just have to call var temp:Array = maps[valueInput] as Array;.
If you really don't want to do that and stick with your n variables, you can write
var index:String = valueInput.toString();
if (index.length == 1)
index = "0" + index; //have the index on two digits "01", "02"
var temp:Array = this["map" + index];
Note that it will only work for your 99 first variables (oh God...)

actionscript remove (concat?) sub-arrays

I have multiple sub-arrays in one huge array - MasterArray- meaning that the sub-arrays are already INSIDE the MasterArray. I would like to "fuse" all of those sub-arrays - to remove those [ ] square brackets.
I would like to avoid the "concat" method because the arrays are already inside the MasterArray. Is there a command/method how to do this?
Thank you.
var englandCities:Array = [London, Manchester, Leeds];
var franceCities:Array = [Paris, Orleans, Avignon];
var europeanCities:Array = [englandCities, franceCities];
I would like to point let's say...to "London" nested in the europeanCities array somehow.
After I try to trace it, it gives me "englandCities", which makes sense.
trace(europeanCities[0]);
// displays "englandCities"
// how can I make it display "London" ?
How can I make the europeanCities array to display "London" ?
I NEED TO REMOVE THOSE SQUARE BRACES from the "europeanCities" array WITHOUT using the concat() thingie...
OKAY let me rephrase this a bit. My master array:
var europeanCities:Array = [englandCities, franceCities];
equals to
[[London, Manchester, Leeds], [Paris, Orleans, Avignon]];
am I right? And now, how to remove the inner brackets in order to get something like this:
[London, Manchester, Leeds, Paris, Orleans, Avignon];
And please, keep in mind, that the array is much longer than englandCities and frenchCities....there are like...30 different Cities.
You can concat those together easily, and it really is the simplest option:
var englandCities:Array = ["London", "Manchester", "Leeds"];
var frenchCities:Array = ["Paris", "Orleans", "Avignon"];
var masterArray:Array = [englandCities, frenchCities];
var europeanCities:Array = new Array();
for each(var country:Array in masterArray) {
europeanCities = europeanCities.concat(country);
}
trace(europeanCities); // London,Manchester,Leeds,Paris,Orleans,Avignon
I'm not sure I understand your reason for avoiding concat for this, unless the issue is it that you don't want to duplicate the values. (So modifying englandCities[0] will also modify europeanCities[0].)
If your cities are Objects rather than primitive Strings, a concatenated Array will work fine. If they are primitives though, there's no way to do this with an Array. You could however write a function to provide similar behaviour like this:
var englandCities:Array = ["London", "Manchester", "Leeds"];
var frenchCities:Array = ["Paris", "Orleans", "Avignon"];
var allCities:Array = [englandCities, frenchCities];
function europeanCities(id:int):String {
var cityID:uint = 0;
while (id > allCities[cityID].length - 1) {
id -= allCities[cityID].length;
cityID++;
}
return allCities[cityID][id];
}
trace (europeanCities(0)); // London
trace (europeanCities(5)); // Avignon
Create an empty array, then traverse the masterArray taking any sub-arrays, and do a concat() for your new array. This will make you another array that's flat, without disturbing master array.
I just write this here because it is possible.
If you insist on not using concat here is one bad solution:
// join elements into a comma delimited string
var s: String = europeanCities.join(',');
// Split the string with delimiter as commas
europeanCities = s.split(',');
Since the subarray elements automatically will be joined with ',' regardless of join delimiter and our join delimiter is already ',' this will work.
But this solution is cpu intensive and not optimal.

Splice then re-index array in ActionScript 3

I want to remove the first four indexes from the array using splice(), then rebuild the array starting at index 0. How do I do this?
Array.index[0] = 'one';
Array.index[1] = 'two';
Array.index[2] = 'three';
Array.index[3] = 'four';
Array.index[4] = 'five';
Array.index[5] = 'six';
Array.index[6] = 'seven';
Array.index[7] = 'eight';
Array.splice(0, 4);
Array.index[0] = 'five';
Array.index[1] = 'six';
Array.index[2] = 'seven';
Array.index[3] = 'eight';
I am accessing the array via a timer, on each iteration I want to remove the first four indexes of the array. I assumed splice() would remove the indexes then rebuild the array starting at 0 index. it doesn't, so instead what I have done is created a 'deleteIndex' variable, on each iteration a +4 is added to deleteIndex.
var deleteIndex:int = 4;
function updateTimer(event:TimerEvent):void
{
Array.splice(0,deleteIndex);
deleteIndex = deleteIndex + 4;
}
What type of object is "Array" in the code you have shown? The Flash Array object does not have a property named "index". The Array class is dynamic, which means that it let's you add random properties to it at run time (which seems to be what you are doing).
In any case, if you are using the standard Flash Array class, it's splice() method updates the array indexes automatically. Here is a code example that proves it:
var a:Array = [1,2,3,4,5];
trace("third element: ", a[2]); // output: 3
a.splice(2,1); // delete 3rd element
trace(a); // output: 1,2,4,5
trace(a.length); // ouput: 4
trace("third element: ", a[2]); // output: 4
If I am understanding what you want correctly, you need to use the unshift method of Array.
example :
var someArray:Array = new Array(0,1,2,3,4,5,6,7,8);
someArray.splice(0,4);
somearray.unshift(5,6,7,8);
Also, you are using the Array Class improperly, you need to create an instance of an array to work with first.
The question is confusing because you used Array class name instead of an instance of an array. But as the commenter on this post said, if you splice elements, it automatically re-indexes.
im not sure what you want to do, but Array=Array.splice(0,4) should fix somethin..