Range Over Built in ActionScript

Here we use range to sum the numbers in a slice. Arrays work like this too.

package {
    import flash.display.Sprite;
    public class Main extends Sprite {
        public function Main() {
            var nums:Array = [2, 3, 4];
            var sum:int = 0;
            for each (var num:int in nums) {
                sum += num;
            }
            trace("sum:", sum);

            // range on arrays and slices provides both the index and value
            for (var i:int = 0; i < nums.length; i++) {
                if (nums[i] == 3) {
                    trace("index:", i);
                }
            }

            // range on map iterates over key/value pairs
            var kvs:Object = {"a": "apple", "b": "banana"};
            for (var k:String in kvs) {
                trace(k + " -> " + kvs[k]);
            }

            // range can also iterate over just the keys of a map
            for (var k:String in kvs) {
                trace("key:", k);
            }

            // range on strings iterates over Unicode code points
            var str:String = "go";
            for (var j:int = 0; j < str.length; j++) {
                trace(j, str.charCodeAt(j));
            }
        }
    }
}

To run the program, include the above code in an ActionScript file and compile it using the Flex SDK.

$ mxmlc Main.as
$ Main.swf

Running the compiled SWF file will output:

sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111

Now that we can run and build basic ActionScript programs, let’s learn more about the language.