I have not found any documentation and tutorials for using the thisObject parameter within the Array class in ActionScript 3. It seems that there is a gap in knowledge of how to use this, and it could save some people a lot of coding. I think it comes from Adobe copying Javascript docs for Array, essentially (which does not provide much help in using thisObject, either).
thisObject replaces what is considered the “this” scope. If you are working in some class, and type this.someVar, you are accessing the class-level variable called someVar. This is pretty simple.
Within an Array.filer() call, though, you probably want to have the scope be something else. Often, you will see code with hard-coded values used for filter, every, some, etc. Like
array.filter(someCallbackFunction); [...] public function someCallbackFunction(element:*, index:int, arr:Array):Boolean { element.isActive = true; }
In someCallbackFunction, the value “true” is hard-coded. What if you want to test against “false”? That would require another function. Not very good OOP.
If the hard-coded values could be a variable instead, that would make things much easier to understand. thisObject supplies a context for using variables.
If you have an array of objects of type SampleClass, and you want to filter according to some variable in the class, set thisObject to the value to compare. For example:
var testVal:String = "something"; array.filter(someCallbackFunction, testVal); [...] public function someCallbackFunction(element:*, index:int, arr:Array):Boolean { element.isActive = this; }
Now someCallbackFunction uses testVal as the local context; this actually equals testVal, so you can just use this to reference the data, as above.
Here is a working method example:
public function testArray() { var arr:Array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var filterValArr:Array = [4, 8]; var filtARr:Array; var val:int = filterValArr.length; for (var i:int = 0; i < val; i++) { filtARr = arr.filter( function(item:*, index:int, array:Array):Boolean { return item > this; }, filterValArr[i] ); trace("filtARr test " + i + " = " + filtARr); } }
- 30 -
Very helpful thanks!
Using your example, I’ve added a new property to my ToolBox class in order to help me filtering arrays with an other one. Here the code :
//property of the Tools class
public static var notInArray:Function = function(item:*, index:int, array:Array):Boolean
{
return this.indexOf(item) == -1;
}
Thus, you can call anywhere in your code :
wantedItemsArray = allItemsArray.filter(Tools.notInArray,unwantedItemsArray);
Hope this can help someone, someday ^^
謝謝你, 這個範例相當實用!
Very helpful! thx
thank you!