document.write("");
for (property in document) {
document.write("" + property + " | " + document[property] + " | ");
}
for-of loop: returns each value in an array:
let groceries = ["bread", "milk", "peanut butter"];
// Display all elements in groceries array
for (let item of groceries) {
console.log(item);
}
forEach function: Allows the user to provide a function that will
be applied to each element of an array:
let groceries = ["bread", "milk", "peanut butter"];
// Display all elements in groceries array
groceries.forEach(function(item, index) {
console.log(index + " - " + item);
});
Arrays
- JavaScript arrays are objects, not built-in data types
- You can create either an uninitialized or an initialized array
type | example | effect |
uninitialized array | x = new Array(10) |
create an array with 10 elements |
initialized array | x = new Array(10, 20, 30) |
create an array with 3 elements: 10, 20, and 30 |
initialized array | x = [10, 20, 30]; |
create an array with 3 elements: 10, 20, and 30 |
- String arrays
- Splitting a string into an array: array = string.split(" "):
The parameter is a character on which to split the string, in
this case, a blank character. You
cannot use a fancy regular expression and you cannot have
multiple occurrences of the character separating the strings.
For example, if you have:
then your array will be ["Brad", "Vander", " ", "Zanden"].
- Joining array elements to form a string: string = array.join(","):
The parameter is a separator character
- Sorting arrays
- sorted_array = array.sort(): sorts array alphabetically
and stores the result in a new array called sorted_array.
- numeric sorting or other types of sorting can be accomplished by
passing to the sort method a comparison function that takes two parameters,
a and b to be compared. The comparison
function should return a negative number if a should appear
before b, 0, if they are the same, and a positive number if
a should appear after b. For example:
function numcompare(a, b) {
return a - b;
}
sorted_nums = nums.sort(numcompare);
|
IIf you want you can create an anonymous function or a so-called
arrow function:
sorted_nums = nums.sort((a,b) => a - b);
Functions
- Declared using the keyword function
- Can take any number of arguments
- return keyword returns a value
- Called in the normal C/C++ manner
- Primitive types passed by value and arrays/objects passed by reference
- Use let or var to declare a variable as local. If you simply use
a variable without declaring it then it will be placed in the global
name space and will remain defined after the function exits.
- Function pointers can be assigned to variables. For example:
a = function () { alert("hi brad!"); }
a();
|
- You can create anonymous "arrow" functions as well. The general form is:
(parameter list) => { code }
If the parameter list is only one variable then you omit the ()'s. Arrow functions
return a function pointer that must be assigned to a variable or passed to a function, as was done in the sort function above.
Objects
- Created using the new keyword
- Deleted using the delete keyword
- "Anonymous" objects can be created using the {} notation: a = {};
- Objects are somewhat like associative arrays in that properties can
be dynamically added to or deleted from an object and properties can
be accessed using either . (dot) or [] (bracket) notation. For
example:
new_obj = {};
new_obj.name = "brad";
new_obj['zip_code'] = 37920;
alert("name = " + new_obj['name']);
alert("zip code = " + new_obj.zip_code);
delete new_obj.name;
|
- Maps: The Map object is a newer alternative to using objects for storing key/value pairs. Common methods and properties of the Map object include:
- The set(key, value) method sets a key/value pair. If the key is new, a new element is added to the map. If the key already exists, the new value replaces the existing value.
- The get(key) method gets a key's associated value.
- The has(key) method returns true if a map contains a key, false otherwise.
- The delete(key) method removes a map element.
- The size property is the number of elements in the map.
The Map object's syntax is clunkier than an object's syntax but a Map
object does have a number of advantages over a regular object:
- Keys can be any type, not just strings.
- A Map has a .size() function that allows you to easily determine
the number of keys in the map.
- You can access the key/value pairs in the order in which they
were inserted using a for..of loop. For example:
let stateCapitals = new Map();
stateCapitals.set("AR", "Little Rock");
stateCapitals.set("CO", "Denver");
stateCapitals.set("NM", "Santa Fe");
console.log("All capitals:");
for (let [state, capital] of stateCapitals) {
console.log(state + " is " + capital);
}
- Constructor functions: You can create a constructor function
by naming the function after the object you wish to create
and using the this variable to assign values to the
object's properties. For example:
function Account(cust_name, initial_deposit, date) {
this.name = cust_name;
this.balance = initial_deposit;
this.origination_date = date;
}
new_acct = new Account("Brad", 500, '4/10/08');
alert("name: " + new_acct.name + '\n' +
"deposit: " + new_acct.balance + '\n' +
"date: " + new_acct.origination_date);
|
- Adding methods to objects: You can add a method to an object
by defining a function and then assigning a pointer to the
function to one of the object's properties.
- Creating an inheritance chain: You can make one object inherit
from another object by setting the object's prototype
property to an instance of the appropriate prototype object.
For example:
function C() {
this.height = 25;
}
function B() {
this.width = 20;
}
B.prototype = new C();
var b1 = new B();
alert(b1.height); // prints 25
Note that B is a function object with a prototype property,
which is what we are setting.
|