Wednesday, May 1, 2013

Functions, Arrays, Objects in JavaScript: Part I

These are examples of creating a function, array, and object in JavaScript. The function below calls an expression invocation (Math.PI). An expression invocation is JavaScript equivalent to a built-in function.  A for loop sends 11 consecutive numeric arguments to the new function:




var PI_function = function(x) {return ((Math.PI) * x);}
for (i in [1,2,3,4,5,6,7,8,9,10,11]) {console.log(PI_function(i))}
0
3.141592653589793
6.283185307179586
9.42477796076938
12.566370614359172
15.707963267948966
18.84955592153876
21.991148575128552
25.132741228718345
28.274333882308138
31.41592653589793

We can do something similar by creating an array of the same values and then using a for statement with the increment operator to enumerate each element of an array that begins with index '0'.

var PI_array = [
(Math.PI),
((Math.PI) * 2),
((Math.PI) * 3),
((Math.PI) * 4),
((Math.PI) * 5),
((Math.PI) * 6),
((Math.PI) * 7),
((Math.PI) * 8),
((Math.PI) * 9),
((Math.PI) * 10)
];

for(i=0;i < 11;i++)console.log((PI_array[i]));

3.141592653589793
6.283185307179586
9.42477796076938
12.566370614359172
15.707963267948966
18.84955592153876
21.991148575128552
25.132741228718345
28.274333882308138
31.41592653589793

We can also create an object which will have corresponding properties:
When we access each of those objects with their corresponding properties, the desired value is obtained:

PI_object.PI
3.141592653589793
PI_object.PI2
6.283185307179586
PI_object.PI3
9.42477796076938
...

var PI_object = {
PI:   (Math.PI),
PI2:  ((Math.PI) * 2),
PI3:  ((Math.PI) * 3),
PI4:  ((Math.PI) * 4),
PI5:  ((Math.PI) * 5),
PI6:  ((Math.PI) * 6),
PI7:  ((Math.PI) * 7),
PI8:  ((Math.PI) * 8),
PI9:  ((Math.PI) * 9),
PI10: ((Math.PI) * 10)
};

// We can use a for in statement to print all the properties of our object:

for (i in PI_object) {console.log(i)}
PI
PI2
PI3
PI4
PI5
PI6
PI7
PI8
PI9
PI10

No comments:

Post a Comment