Thursday, August 16, 2012

Java Script : Array of functions

Another intersting concept that I came across:
Java Script allows you to create an array of functions, took me a while to make this work but I finally got it. Here is example of how to do this:

<!DOCTYPE html>
<html>
<head>
    <title>Array of functions</title>
<script type="text/javascript">
  
function transform(array)
   {
         function makeFunction(value)
             {return function()
                {
                    return value;
                }
             }
         
       var output = new Array();
       for(var i = 0; i < array.length; ++i)
          {
              output[i] = makeFunction(array[i]);
          }
       return output;
   }
</script>
</head>
<body>
<script type="text/javascript">
myArray = [1,2,3,4,5];
myArray = transform(myArray);
for(var i =0 ; i < myArray.length; ++i)
{
    alert( myArray[i]());
}
</script>

</body>
</html>

1 comment:

  1. Thanks for a wonderful share. Your article has proved your hard work and experience you have got in this field. Brilliant .i love it reading. r语言代写

    ReplyDelete