JavaScript:
Arrays and Objects
Computer Science and Engineering College of Engineering The Ohio State University
Copyright By Assignmentchef assignmentchef
Given: roster of students (an array)
Write a JavaScript program that outputs an html list of students (name and midterm score) whose gpa is > 3.0, such that the list is sorted by midterm score
1. Xi Chen (85)
Computer Science and Engineering The Ohio State University
Arrays: Basics
Numbered starting at 0
Indexed with [ ]
Property length is # of elements
var sum = 0;
for (var i = 0; i < n.length; i++) {sum += n[i]; }Computer Science and Engineering The Ohio State UniversityArray Instantiation/InitializationInstantiate with newvar n = new Array(3);Initially, each element is undefinedNote: Elements can be a mix of typesn[0] = 10;n[1] = “hi”;n[2] = new Array(100);Array literals usually preferredvar n = [10, 20, 30, 40];var m = [“hi”, , “world”, 3.14];[3, “hi”, 17, [3, 4]].length == 4Computer Science and Engineering The Ohio State UniversityDynamic SizeArrays can growComputer Science and Engineering The Ohio State Universityvar n = [“tree”, 6, -2]; n.length == 3 //=> true n[8] = 17;
n.length == 9 //=> true
Arrays can shrink
n.length = 2;
// n is now [tree, 6 ]
Arrays are Dynamic
Computer Science and Engineering The Ohio State University
var n = [];
Arrays are Dynamic
Computer Science and Engineering The Ohio State University
var n = [];
Arrays are Dynamic
Computer Science and Engineering The Ohio State University
Arrays are Dynamic
Computer Science and Engineering The Ohio State University
Arrays are Dynamic
Computer Science and Engineering The Ohio State University
n[3] = 3.14;
Arrays are Dynamic
Computer Science and Engineering The Ohio State University
1 undefined 2 undefined 3
Arrays are Dynamic
Computer Science and Engineering The Ohio State University
1 undefined 2 undefined 3
n[1] = hi;
Arrays are Dynamic
Computer Science and Engineering The Ohio State University
2 undefined 3
Accessors: Searching
Computer Science and Engineering The Ohio State University
Find occurrence: indexOf/lastIndexOf Returns -1 if not found
indexOf(element[, startIndex]) lastIndexOf(element[, lastIndex])
Optional parameter: start/end index Uses strict equality (===)
var i = n.indexOf(elt);
while (i != -1) {
report(i);
i = n.indexOf(elt, i + 1);
Accessors: Extracting
Computer Science and Engineering The Ohio State University
None of the following change the array Return a new array/string with result
Concatenate: concat concat(a1, a2, , aN) var d = n.concat(n);
Extract a sub-section: slice slice(startIndex, endIndex)
k = n.slice(1, 3); // k is n[1], n[2]
Combine into string: join join(separator)
s = n.join( ); // default is ,
Mutators: Growing/Shrinking
Computer Science and Engineering The Ohio State University
Add/remove from end: push/pop var n = [10, 20];
newLength = n.push(30, 40); //=> 4 lastValue = n.pop(); //=> 40
Add/remove from beginning: unshift/shift
var n = [10, 20];
newLength = n.unshift(30, 40); //=> 4 firstValue = n.shift(); //=> 30
Push/shift gives FIFO queue
Push Example
function findAll(n, elt) {
var indices = [];
var i = n.indexOf(elt);
while (i != -1) {
indices.push(i);
i = n.indexOf(elt, i + 1);
return indices;
Computer Science and Engineering The Ohio State University
Mutators: Delete/Insert/Replace
Computer Science and Engineering The Ohio State University
Delete/insert/replace sub-array: splice splice (index, howMany[, e1, e2, , eN])
Modifies array (cf. slice, an accessor)
Returns array of removed elements
var magic = [34, -17, 6, 4];
var removed = magic.splice(2, 0, 13); // removed is []
// magic is [34, -17, 13, 6, 4]
removed = magic.splice(3, 1, hi, yo);
// removed is [6]
// magic is [34, -17, 13, hi, yo, 4]
Mutators: Rearrange
Computer Science and Engineering The Ohio State University
Transpose all elements: reverse var n = [5, 300, 90]; n.reverse(); // n is [90, 300, 5]
Order all elements: sort
var f = [blue, beluga,killer]; f.sort(); // f is
// [beluga, blue,
n.sort(); // n is [300, 5, 90]
Mutators: Rearrange
Computer Science and Engineering The Ohio State University
Transpose all elements: reverse var n = [5, 300, 90]; n.reverse(); // n is [90, 300, 5]
Order all elements: sort
var f = [blue, beluga,killer]; f.sort(); // f is
// [beluga, blue,
n.sort(); // n is [300, 5, 90]
Problem: Default ordering is based on string representation (lexicographic) Solution: Use a function that compares
Sorting with Comparator
Computer Science and Engineering The Ohio State University
A comparator (a, b) returns a number
< 0 iff a is smaller than b == 0 iff a is same size as b > 0 iff a is greater than b
function lenOrder(a, b) {
return a.length b.length;
function compareNumbers(a, b) {
return a b; }
Sorting with Comparator
Computer Science and Engineering The Ohio State University
Optional argument to sort
sort([compareFunction])
names.sort(lenOrder);
n.sort(compareNumbers);
n.sort(function(a, b) {
return a b;
Iteration: Logical Quantification
Computer Science and Engineering The Ohio State University
function isBig(elt, index, array) {
return (elt >= 10);
Universal quantification: every
[5, 8, 13, 44].every(isBig); // false [51, 18, 13, 44].every(isBig); // true
Existential quantification: some [5, 8, 13, 44].some(isBig); // true [5, 8, 1, 4].some(isBig); // false
Neither modifies original array
Iteration: Filter
Computer Science and Engineering The Ohio State University
Pare down an array based on a
condition: filter filter(predicate) predicate(element, index, array)
Returns a new array, with elements that satisfied the predicate
Does not modify the original array Example
t = [12, 5, 8, 13, 44].filter(isBig);
Iteration: Map
Computer Science and Engineering The Ohio State University
Transform an array into a new array, element by element: map
E.g. an array of strings into an array of their lengths
[hi, there, world] -> [2, 5, 5]
map(callback) callback(element, index, array)
len = names.map(function(elt, i, a) {
return elt.length
Computer Science and Engineering The Ohio State University
Transform an array into a new array,
element by element
Uses block to calculate each new value a.map { |item| block }
resulting array
Iteration: For Each
Computer Science and Engineering The Ohio State University
Similar to map, but preferred for side-
effects and changing an array in place
forEach(callback) callback(element, index, array)
function logArrayElts(elt, i, array) {
console.log([ + i + ] = + elt);
[2, 5, 9].forEach(logArrayElts);
Iteration: Reduce
Applies a binary operator between all the elements of the array
E.g., to sum the elements of an array
[15, 10, 8] -> 0 + 15 + 10 + 8 -> 33 reduce(callback[, initialValue]) callback(previous, elt, index, array) Examples
function sum(a, b) { return a + b; } function acc(a, b) { return a + 2 * b; } [2, 3, 7, 1].reduce(sum) //=> ?
[2, 3, 7, 1].reduce(sum, 0) //=> ?
[2, 3, 7, 1].reduce(sum) //=> ? [2, 3, 7, 1].reduce(acc) //=> ? [2, 3, 7, 1].reduce(acc, 0) //=> ?
Computer Science and Engineering The Ohio State University
Iteration: Reduce
Applies a binary operator between all the elements of the array
E.g., to sum the elements of an array
[15, 10, 8] -> 0 + 15 + 10 + 8 -> 33 reduce(callback[, initialValue]) callback(previous, elt, index, array) Examples
function sum(a, b) { return a + b; } function acc(a, b) { return a + 2 * b; } [2, 3, 7, 1].reduce(sum) //=> 13
[2, 3, 7, 1].reduce(sum, 0) //=> 13
[2, 3, 7, 1].reduce(sum) //=> 571 [2, 3, 7, 1].reduce(acc) //=> 24 [2, 3, 7, 1].reduce(acc, 0) //=> 26
Computer Science and Engineering The Ohio State University
Recall: Rubys Reduction Chain
Computer Science and Engineering The Ohio State University
resulting value
Iteration: Reduce
Examples with anonymous functions
[2, 3].reduce( function(a, b) {
return a + b;
}); //#=> ?
[[0, 1], [2, 3], [4, 5]].reduce(
function(a, b) {
return a.concat(b);
}); //#=> ?
Computer Science and Engineering The Ohio State University
Iteration: Reduce
Examples with anonymous functions
[2, 3].reduce( function(a, b) {
return a + b;
}); //#=> 5
[[0, 1], [2, 3], [4, 5]].reduce(
function(a, b) {
return a.concat(b);
}); //#=> [0, 1, 2, 3, 4, 5]
Computer Science and Engineering The Ohio State University
Given: roster of students (an array)
Write a JavaScript program that outputs an html list of students (name and midterm score) whose gpa is > 3.0, such that the list is sorted by midterm score
1. Xi Chen (85)
Computer Science and Engineering The Ohio State University
Example Input
var roster =
[ { name: ,
midterm: 80 },
{ name: Xi Chen,
midterm: 85 },
{ name: ,
midterm: 74 },
{ name: ,
midterm: 68 } ];
Computer Science and Engineering The Ohio State University
One Solution
document.writeln(
- );
document.writeln(
roster.filter(function (e, i, a) {
return e.gpa > 3.0;
}).sort(function (a, b) {
return b.midterm a.midterm;
}).map(function (e, i, a) {
return e.name + (
+ e.midterm + );
}).join( - ));
document.writeln(
);
Computer Science and Engineering The Ohio State University
Computer Science and Engineering The Ohio State University
Array accessors and mutators
Accessors: indexOf, slice
Mutators for extraction: push/pop, unshift/shift, splice
Mutators for rearranging: reverse, sort
Array iteration
Quantification: every, some, filter
Map (foreach for side-effects & mutating) Reduce
Computer Science and Engineering The Ohio State University
var d = new Dog();
d instanceof Dog; //#=> true d instanceof Pet; //#=> true
Questions:
What is Dog? (A class? An interface? ) What is Pet?
How are they related? Draw the hierarchy
Computer Science and Engineering The Ohio State University
What is an Object?
Property: a key/value pair (aka name /value)
Creating an object, literal notation
var myCar = { make: Acura,
year: 1996,
plate: NKR462 }; To access/modify an objects properties:
myCar.make = Ford; //cf. Ruby myCar[year] = 2006;
var str = ate;
myCar[pl + str] == NKR463;
Object: a partial map of properties Keys must be unique
Computer Science and Engineering The Ohio State University
Object Properties
Computer Science and Engineering The Ohio State University
make year plate
Ford 2006 NKR463
Arrays vs Associative Arrays
Computer Science and Engineering The Ohio State University
0 4 1 hi
0 true 1 true 2 false
age 4 greeting hi
0 true 1 true 2 false
Dynamic Size, Just Like Arrays
Computer Science and Engineering The Ohio State University
Objects can grow
myCar.state = OH; // 4 properties var myBus = {};
myBus.driver = true; // adds a prop myBus.windows = [2, 2, 2, 2];
Objects can shrink
delete myCar.plate;
// myCar is now {make: Ford, // year: 2006, state: OH}
Object Properties
Computer Science and Engineering The Ohio State University
make year plate
Ford 2006 NKR463
Object Properties
Computer Science and Engineering The Ohio State University
myCar.state = OH;
make year plate state
Ford 2006 NKR463 OH
Object Properties
Computer Science and Engineering The Ohio State University
delete myCar.plate;
make year state
Ford 2006 OH
Testing Presence of Key
Computer Science and Engineering The Ohio State University
Boolean operator: in propertyName in object
Evaluates to true iff object has the indicated property key
make in myCar //=> true speedometer in myCar //=> false OH in myCar //=> false
Property names are strings
Iterating Over Properties
Computer Science and Engineering The Ohio State University
Iterate using forin syntax
for (property in object) { object[property]
for (p in myCar) {
document.write(p +: + myCar[p]);
Notice [] to access each property
The value of a property can be:
A primitive (boolean, number, string, null)
A reference (object, array, function) var temp = function(sound) {
play(sound);
return 0; }
myCar.honk = temp; More succinctly:
myCar.honk = function(sound) {
play(sound);
Computer Science and Engineering The Ohio State University
Example: Method
var myCar = {
make: Acura,
year: 1996,
plate: NKR462,
honk: function(sound) {
play(sound);
Computer Science and Engineering The Ohio State University
Object Properties
Computer Science and Engineering The Ohio State University
make year plate honk
Acura 1996 NKR462
play(sound);
Keyword this in Functions
Computer Science and Engineering The Ohio State University
Recall distinguished formal parameter
x.f(y, z); //x is the distinguished argmt.
Inside a function, keyword this
function report() {
return this.plate + this.year;
At run-time, this is set to the distinguished
argument of invocation
myCar = {plate: NKR462, year: 1996}; yourCar = {plate: 340, year: 2013}; myCar.register = report;
yourCar.info = report; myCar.register(); //=> NKR4621996 yourCar.info(); //=> 2353
Object Properties
plate NKR462 year 1996
Computer Science and Engineering The Ohio State University
plate 340 year 2013
return this.plate
+ this.year;
Constructors
Computer Science and Engineering The Ohio State University
Any function can be a constructor When calling a function with new:
1. Make a brand new (empty) object
2. Call the function, with the new object as the
distinguished parameter
3. Implicitly return the new object to caller
A constructor often adds properties to the new object simply by assigning them
function Dog(name) {
this.name = name; // adds 1 property // no explicit return
var furBall = new Dog(Rex);
Naming convention: Functions intended to be constructors are capitalized
function Circle(x, y, radius) {
this.centerX = x;
this.centerY = y;
this.radius = radius;
this.area = function() {
return Math.PI * this.radius *
this.radius;
var c = new Circle(10, 12, 2.45);
Computer Science and Engineering The Ohio State University
Creating a Circle Object
Computer Science and Engineering The Ohio State University
var c = new Circle(10, 12, 2.45);
this.centerX = x;
this.centerY = y;
Etc
Creating a Circle Object
Computer Science and Engineering The Ohio State University
var c = new Circle(10, 12, 2.45); Circle
this.centerX = x;
this.centerY = y;
Etc
Creating a Circle Object
centerX centerY 12
Computer Science and Engineering The Ohio State University
var c = new Circle(10, 12, 2.45); Circle
this.centerX = x;
this.centerY = y;
Etc
return Math.PI *
this.radius *
this.radius
Creating a Circle Object
Computer Science and Engineering The Ohio State University
var c = new Circle(10, 12, 2.45); Circle
this.centerX = x;
this.centerY = y;
Etc
return Math.PI *
this.radius *
this.radius
centerX centerY 12
Creating a Circle Object
Computer Science and Engineering The Ohio State University
var c = new Circle(10, 12, 2.45); Circle
this.centerX = x;
this.centerY = y;
Etc
return Math.PI *
this.radius *
this.radius
centerX centerY 12
CS: assignmentchef QQ: 1823890830 Email: [email protected]
Reviews
There are no reviews yet.