FANDOM


Array of objects

Arrays of Objects is a talk-through in which Pamela demonstrates how to store arrays of Objects.

She starts out with a program previously used in the Variables section, which defines a function to draw Winston (called, appropriately enough, drawWinston...), and then includes four separate calls to that function, each with a different x and y parameter. She then demonstrates how, instead, two arrays could be used to store the corresponding x and y positions, and looped through.

She goes on to explain that there's an easier way though.  A single array can be created, including within it multiple objects, each of which stores one set of x and y coordinates.  By then looping through those objects, the same drawing can be created with just that one array:

var positions = [
  {x: 99, y: 117},
  {x: 294, y: 117},
  {x: 101, y: 316},
  {x: 294, y: 316} 
];
for (var i = 0; i < positions.length; i++) {
    drawWinston(positions[i].x, positions[i].y);
}

Finally, she demonstrates that the drawWinston function can actually be modified to expect an object as input, rather than requiring the individual x and y values:

var drawWinston = function(facePosition) {
    var faceX = facePosition.x;
    var faceY = facePosition.y;

// which can then be called by:

for (var i = 0; i < positions.length; i++) {
    drawWinston(positions[i]);
}


☀ All Khan Academy content is available for free at: www.khanacademy.org

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.